Generic selectors
Exact matches only
Search in title
Search in content

Python Keywords – Everything You MUST Know About Them

Python keywords are the reserved words. They are used by python interpreter to understand the program. Keywords define the structure of programs. We can’t use keywords to name program entities such as variables, class, and functions.

How Many Keywords in Python?

Python has a lot of keywords. The number keeps on growing with the new features coming in python.

Python 3.7.3 is the current version as of writing this tutorial. There are 35 keywords in Python 3.7.3 release.

We can get the complete list of keywords using python interpreter help utility.

$ python3.7
>>> help()
help> keywords

Here is a list of the Python keywords.  Enter any keyword to get more help.

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

Brief Introduction of the Python Keywords

We will cover all the python keywords in future tutorials. Let’s get the basic idea of the purpose and usage of these keywords.

Serial NoKeywordDescriptionExample
1Falseinstance of class bool.x = False
2classkeyword to define a class.class Foo:     pass
3fromclause to import class from modulefrom collections import OrderedDict
4orBoolean operatorx = True or False
5Noneinstance of NoneType objectx = None
6continuecontinue statement, used in the nested for and while loop. It continues with the next cycle of the nearest enclosing loop.numbers = range(1,11) for number in numbers:     if number == 7:         continue
7globalglobal statement allows us to modify the variables outside the current scope.x = 0 def add():     global x     x = x + 10 add() print(x) # 10
8passPython pass statement is used to do nothing. It is useful when we require some statement but we don’t want to execute any code. def foo():     pass
9Trueinstance of bool class.x = True
10defkeyword used to define a function. def bar():     print(“Hello”)
11ifif statement is used to write conditional code block. x = 10 if x%2 == 0:     print(“x is even”) # prints “x is even”
12raiseThe raise statement is used to throw exceptions in the program. def square(x):     if type(x) is not int:     raise TypeError(“Require int argument”)     print(x * x)
13andBoolean operator for and operation. x = True y = Falseprint(x and y) # False
14delThe del keyword is used to delete objects such as variables, list, objects, etc. s1 = “Hello” print(s1) # Hello del s1 print(s1) # NameError: name ‘s1’ is not defined
15importThe import statement is used to import modules and classes into our program. # importing class from a module from collections import OrderedDict# import module import math
16returnThe return statement is used in the function to return a value. def add(x,y):     return x+y
17asPython as keyword is used to provide name for import, except, and with statement. from collections import OrderedDict as od import math as mwith open(‘data.csv’) as file:     pass     # do some processing on filetry:     pass except TypeError as e:     pass
18elifThe elif statement is always used with if statement for “else if” operation. x = 10if x > 10:     print(‘x is greater than 10’) elif x > 100:     print(‘x is greater than 100’) elif x == 10:     print(‘x is equal to 10’) else:     print(‘x is less than 10’)
19inPython in keyword is used to test membership. l1 = [1, 2, 3, 4, 5]if 2 in l1:     print(‘list contains 2’)s = ‘abcd’if ‘a’ in s:     print(‘string contains a’)
20tryPython try statement is used to write exception handling code. x = ” try:     i = int(x) except ValueError as ae:     print(ae)# invalid literal for int() with base 10: ”
21assertThe assert statement allows us to insert debugging assertions in the program. If the assertion is True, the program continues to run. Otherwise AssertionError is thrown. def divide(a, b):     assert b != 0     return a / b
22elseThe else statement is used with if-elif conditions. It is used to execute statements when none of the earlier conditions are True. if False:     pass else:     print(‘this will always print’)
23isPython is keyword is used to test if two variables refer to the same object. This is same as using == operator. fruits = [‘apple’] fruits1 = [‘apple’] f = fruits print(f is fruits) # True print(fruits1 is fruits) # False
24whileThe while statement is used to run a block of statements till the expression is True. i = 0 while i < 3:     print(i)     i+=1# Output # 0 # 1 # 2
25asyncNew keyword introduced in Python 3.5. This keyword is always used in couroutine function body. It’s used with asyncio module and await keywords. import asyncio import timeasync def ping(url):     print(f’Ping Started for {url}’)     await asyncio.sleep(1)     print(f’Ping Finished for {url}’)async def main():     await asyncio.gather(     ping(‘’),     ping(‘’),     )if __name__ == ‘__main__’:     then = time.time()     loop = asyncio.get_event_loop()     loop.run_until_complete(main())     now = time.time()     print(f’Execution Time = {now – then}’)# Output Ping Started for Ping Started for Ping Finished for Ping Finished for Execution Time = 1.004091739654541
26awaitNew keyword in Python 3.5 for asynchronous processing.Above example demonstrates the use of async and await keywords.
27lambdaThe lambda keyword is used to create lambda expressions. multiply = lambda a, b: a * b print(multiply(8, 6)) # 48
28withPython with statement is used to wrap the execution of a block with methods defined by a context manager. The object must implement __enter__() and __exit__() functions. with open(‘data.csv’) as file:
29exceptPython except keyword is used to catch the exceptions thrown in try block and process it.Please check the try keyword example.
30finallyThe finally statement is used with try-except statements. The code in finally block is always executed. It’s mainly used to close resources. def division(x, y):     try:         return x / y     except ZeroDivisionError as e:         print(e)         return -1     finally:         print(‘this will always execute’)print(division(10, 2)) print(division(10, 0))# Output this will always execute 5.0 division by zero this will always execute -1
31nonlocalThe nonlocal keyword is used to access the variables defined outside the scope of the block. This is always used in the nested functions to access variables defined outside. def outer():     v = ‘outer’    def inner():         nonlocal v         v = ‘inner’    inner()     print(v)outer()
32yieldPython yield keyword is a replacement of return keyword. This is used to return values one by one from the function. def multiplyByTen(*kwargs):     for i in kwargs:         yield i * 10a = multiplyByTen(4, 5,) # a is generator object, an iterator# showing the values for i in a:     print(i)# Output 40 50
33breakThe break statement is used with nested “for” and “while” loops. It stops the current loop execution and passes the control to the start of the loop. number = 1 while True:     print(number)     number += 2     if number > 5:         break         print(number) # never executed# Output 1 3 5
34forPython for keyword is used to iterate over the elements of a sequence or iterable object. s1 = ‘Hello’ for c in s1:     print(c)# Output H e l l o
35notThe not keyword is used for boolean not operation. x = 20 if x is not 10:     print(‘x is not equal to 10’)x = True print(not x) # False


Python keywords have specific functions. They are used by the python interpreter to understand the code and execute them. There are 35 keywords in Python. The number will keep on growing with new features.