Python Keywords

Python keywords are reserved words. They are used by python interpreters to understand the program. Keywords define the structure of programs. We can’t use keywords to name program entities such as variables, classes, 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.10.5 is the current stable version as of writing this tutorial. There are 35 keywords in Python 3.10.5 release.

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

$ python3.10
>>> 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

Python Keywords List

We can use the “keyword” module to get the list of keywords.

% python3
Python 3.10.5 (v3.10.5:f377153967, Jun  6 2022, 12:36:10) [Clang 13.0.0 (clang-1300.0.29.30)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import keyword
>>> keyword.kwlist
['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']
>>> len(keyword.kwlist)
35
>>> 
Python Keyword Module Kwlist

Python Soft Keywords

Python 3.9 introduced the concept of soft keywords. We can use soft keywords as variable names and they get special treatment only in the context of the program. As of now, there are two soft keywords – merge and case. We can confirm this using the keyword module.

>>> keyword.softkwlist
['_', 'case', 'match']
>>> 

Why do we need soft keywords?

I think the idea of a soft keyword is introduced to avoid breaking the existing code in case they are used as an identifier. This will give enough time for developers to make appropriate changes to their code.

How to Check if a String is a Keyword?

We can use keyword.iskeyword() function to check if a string is a reserved keyword.

For example, is print a keyword in python?

>>> keyword.iskeyword('print')
False
>>> 

So, print is not a keyword in python.


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(‘askpython.com’), ping(‘python.org’), )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 askpython.com Ping Started for python.org Ping Finished for askpython.com Ping Finished for python.org 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: file.read()
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

Summary

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.

What’s next?

You got a brief idea of keywords in python. Now, you should go through the following tutorials to get the basics of Python programming.

Resources