Menu Close

Python Keywords Tutorial

python keywords

Python Keywords Tutorial

In this Python keywords tutorial we are going to learn Python keywords and identifiers. Keywords in Python are reversed words and identifiers is name given to variables. In previous tutorial we have seen Python Variables and its uses.

If you don’t know about Python Variables, Then click here to know about detail information about Python variables.

Before going through this article. Let’s understand what exactly Python keywords.

What is Python Keywords ?

In Python, keywords are reversed word that means you can not use keyword name as variable name and function name as well as identifier name. Python provide 33 various type of keywords which are used in different works.
Python keywords are case sensitive. In this python keywords tutorial we will see all the python keyword one by one with brief description and example.

How to get Python Keywords ?

To get Python Python keywords list, we have two methods.

  • Using help() function
  • Using keyword module

Get Python keywords using help() function:

help() function is a Python built-in function which are used to get the detail information of any module, function, classes, keywords etc.
To get the all the keywords, you have to open your python interpreter and type help(‘keywords’).

Example

help('keywords')

Output

Python keywords
Python keywords

Information of any particular keyword:

To get the detailed information of any particular keyword, you can also use help() function and pass keyword name inside the function within single or double quotes.

Example

help('False')

Get Python keywords using keyword module:

This is the another way to get the information of python keywords. To get the list of all keywords, you can use keyword built-in module.

Example

import keyword
print(keyword.kwlist)

Output

['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

Let’s see detail information of all the Python keywords one by one.

Description of Python keywords:

True

Return True when argument x is true, otherwise False. This is use in comparison operations or logical operations.

>>> 1==1
True
>>> 10>=1
True
>>> True or False
True

False

Return True when x s true, otherwise False. The built-in True and False are two instance of class bool.

>>> 1==2
False
>>> 10<=1
False
>>> True and False
False

None

In Python, None is special constant in Python that represent the absence of value or null value. It is the object of its own data type.

>>> x = None
>>> y = None
>>> x==y
True

and, or, not

and, or and not are the logical operations in Python.
and return True when all the condition seperated by and operator return True.
or return True when any condition seperated by or operator return True.
not operator is used to invert the truth value.

>>> 12 > 5 and 5 < 10
True
>>> 12 > 5 or 5 < 2
True
>>> x = 12
>>> not x < 20
False

as

as keyword is used to assign the alias name of module during importing of module.it mean you can give the another name of module when import the module.

>>> from datetime import datetime as dt
>>> dt.now()
datetime.datetime(2020, 9, 27, 16, 18, 58, 832419)

assert

assert is used to debugging purpose:

>>> a = 10
>>> assert a > 12
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError

async, await

async and await keyword provide by the Python asyncio module. async keyword specifies that a function executed asynchronously and await keyword make the program wait for particular second.

import asyncio
async def do_something():
    print('Hello, this is')
    await asyncio.sleep(5)
    print('Programming Funda')
	
	
#To run the above program you have to use below command.
asyncio.run(do_something())

Output

Hello, this is
Programming Funda

class

class keyword is used to create user defined class in Python. class is collection of attributes and methods.

class Name:
    def __init__(self, fname, lname):
        self.fname = fname
        self.lname = lname
    def fullname(self):
        print(f"My name is {self.fname} {self.lname}")


#To ruun this program, you have to use following.
x = Name('Vishvajit', 'Rao')
x.fullname()

Output

My name is Vishvajit Rao

def

def keyword is used to create user defined function in Python. In Python function is block of code which are used to perform a particular task.

def fullname(fname, lname):
    print(f"My name is {fname} {lname}")
	
#To run above function, you have to call the function with parameter by using function name.
fullname('Vishvajit', 'Rao') 

Output

My name is Vishvajit Rao

del

del keyword is used delete reference to an object.

a = 10
print(a)
del a
print(a)

Output

10
Traceback (most recent call last):
  File "c:\Users\Vishvajit\Desktop\testing\test.py", line 4, in <module>
    print(a)
NameError: name 'a' is not defined

if, else, elif

if, else and elif statement are used to with condition statement or decision making.
When you want to test some condition and execute a block of code if the condition is true, Then you can use if and else statement. elif statement is used to execute a block of code when previous condition is False.

def testing(n):
    if n==1:
        print('One')

    elif n==2:
        print('Two')

    else:
        print('Something else')


testing(1)
testing(2)
testing(5)

Output

One
Two
Something else

except, raise, try

except, raise and try python keywords are used for exception handling.
try: try block is used to raise the exception.
except: except block is used to handle the exception which are raise by try block.

def testing(n):
    try:
        result = 1/n
        print(result)
    except:
        print('I have handled the exception')


testing(10)
testing(0)

Output

0.1
I have handled the exception

raise: raise block is used to raise the exception.

finally:

finally block is used with try and except block to close the resources or file streams. finally block always execute regardless try block. we have file named test.txt which contain following text.

test.txt:
This file is created only demo purpose.

Now we will read all the text from test.txt file using open() function and close inside finally block.

def testing():
    try:
        f=  open('test.txt', 'r')
        print(f.read())
    except:
        print('I have handled the exception')

    finally:
        f.close()   
testing()

Output

This is only demo purpose.

for

for loop is used for looping. for loop is used, When you want to execute a block of code specific number of times.

for i in range(1, 6):
    print('Programming Funda.com')

Output

Programming Funda.com
Programming Funda.com
Programming Funda.com
Programming Funda.com
Programming Funda.com

from, import

import keyword is used to import the module in current namespace.
from keyword is used to import the specific attributes, function and class from namespace.

import math

In above we imported whole math module using import keyword.
Now are going to import sin() function using from import..from keyword.

>>> from math import sin
>>> print(sin(90))
0.8939966636005579

global

In Python, global keyword is used to create global variable inside a function.

def message():
    global x
    x = 'Programming Funda'
    print(x)

message()
x = 'hello'
print(x)

Output

Programming Funda
hello

in

in operator is used to check if sequence (list, tuple, set ) contain value or not.

x = [1,2,3,4,5,6,7]
if 5 in x:
    print('Well done!')

Output

Well done!

is

is operator is used in Python to check object identity. While == is used to check two variable have same value or not.

>>> x = [1,2,3,4,5,6,7]
>>> y = [1,2,3,4,5,6,7]
>>> print(x == y)
True
>>> print(x is y)
False
>>> print(True is True)
True
>>> print(False is False)
True

lambda

lambda function is single line anonymous function.

>>> x = lambda x, y: x * y
>>> print(x(12, 23))
276

nonlocal

nonlocal keyword is used to work with variable inside nested function. Where the variable should not belong to inner function. Use the nonlocal keyword to declare a variable is not local.

def func1():
    x = 'Vishvajit Rao'
    def func2():
        nonlocal x
        x = 'Programming Funda'
    func2()
    return x

print(func1())

Output

Programming Funda

pass

In Python, pass is a null statement. When you don’t want to execute any code inside function then you can use pass statement.

def func1():
    pass

print(func1())

Output

None

return

return statement is used inside a function to exit and return single value from function.

def func1():
    return 'Programming Funda'

print(func1())

while

while loop is used to execute a block of code for specific number of times.

i = 1
while i < 6:
    print('Programming Funda')
    i = i + 1

Output

Programming Funda
Programming Funda
Programming Funda
Programming Funda
Programming Funda

with

The “with” statement is used to wrap the execution of a block with
methods defined by a context manager.

with open('test.txt','r') as file:
    print(file.read())

yield

yield python keyword is sued to create generator.

def generator():
    for i in range(1, 6):
        yield i * i

for i in generator():
    print(i)

Output

1
4
9
16
25

So, we have seen all the keywords in Python in Python with appropriate examples.

Conclusion:

In this Python keywords tutorial, you have learned about Python keywords with description and example.
I think you have not any confusion regarding Python keywords. Python keywords are reversed words that means you can not assign variable, function name, class name and identifier with Python keywords.

If this post helped you, please share it with your friends who want to
learn Python programming from scratch to advanced.

Previous Article
Next Article

Related Posts

Leave a Reply