This post was last Updated on October 9, 2022 by Himanshu Tyagi to reflect the accuracy and up-to-date information on the page.
In this Python tutorial, we will explore a list of Python reserved words and their definitions and code examples. So, if you want to familiarize yourself with all the reserved Python keywords, check out this tutorial until the very end, and don’t forget to share it with other Python developers who are just starting their coding journey.
Also Read: How to Fix Invalid Syntax Error in Python
What are Python Reserved Words?
In Python, keywords are reserved words with predefined syntax and meaning, which cannot be used as identifiers, i.e., Keywords cannot be used as names of the variables, functions, etc.
33 reserved words in Python are used to develop programming instructions. Below is the list of all reserved words/keywords available in Python.
Also Read: How To Copy List in Python
All Python Reversed Words or Keywords With Definitions and Examples
Let’s look into each keyword in detail with a definition and an example.
1. and keyword
And keyword is a logical operator that is used to combine conditional statements. It returns boolean values. It returns True if all the statements are True else, False.
Let’s look into a sample example program where and keyword is used.
number=12 if number>0 and number<=10: print("Given number lies in the range of 0-10") else: print("Given number is greater than 10")
Given number is greater than 10
Also Read: 10 Best Programming Apps To Learn Python
as keyword is used to create an alias for a word. It mainly creates an alias for imported libraries using import statements.
Let’s look into an example program to better understand as keyword in Python.
# create an alias word for numpy import numpy as np # create a numpy array strArray=np.array(['Code','IT','Bro']) print(strArray)
['Code' 'IT' 'Bro']
Also Read: Python Program To Reverse A Number
assert keyword is used while debugging the code. The working of assert is similar to if block in Python, but it throws an AssertionError if the condition is not true.
Let’s look into an example program where the assert keyword is used.
number = 1 # assert when condition is true assert number==1 # assert when condition is false assert number==10
AssertionError Traceback (most recent call last) <ipython-input-3-3256f06e4462> in <module> 5 6 # assert when condition is false ----> 7 assert number==10 AssertionError:
Programmers use break keywords to break out a loop, i.e., either while or for. Let’s look into an example program where the break keyword is used.
for i in range(0,5): if i==3: break print(i) i=i+1
0 1 2
The class keyword is used to create a class. A class represents the blueprint for creating objects. Let’s look into an example program to create a class using the class keyword.
class Car: company='TATA' model='punch' price=948900
Also Read: Increment and Decrement Operators in Python
continue keyword is used to skip the current iteration in a loop and continue with the next iterations. Let’s look into a sample example program that uses the continue keyword.
# skips 3rd iteration for i in range(1,5): if i==3: continue print(i,'iteration') i=i+1
1 iteration 2 iteration 4 iteration
Also Read: Python Dictionary Length [How To Get Length]
def keyword is used to define the function in Python. The syntax to define a function using the def keyword is given below.
The sample program uses the def keyword to define a function.
def sampleFunction(): print('Demo function') sampleFunction()
The del keyword is used to delete the objects in Python. As Python is an object-oriented programming language, everything in Python is an object. Any variable, class, list, tuple, dictionary, etc., comes under an object and can be deleted using the del keyword.
stringobj='Hello World' print(stringobj) del stringobj print(stringobj)
NameError Traceback (most recent call last) <ipython-input-20-dba8419e939f> in <module> 3 4 del stringobj ----> 5 print(stringobj) NameError: name 'stringobj' is not defined
Also Read: What Does The Python Percent Sign Mean?
elif keyword is used in conditional statements after if. It is the same as else if in other programming languages.
Let’s look into a sample example program that uses elif.
score=84 if(score>80): print('A Grade') elif(score>60 and score<80): print('B Grade') elif(score>40 and score<60): print('C Grade') else: print('Fail')
Also Read: How to Create an Empty Array In Python
else keyword is also used in conditional statements along with if and elif. Else block contains what actions to be performed if the condition specified in if/elif is false.
score=84 if(score>40): print('Pass') else: print('Fail')
except keyword is used along with try block. Except block consists of code that executes when the code inside the try block raises an error. So for each try block, there may be multiple except blocks.
Let’s look into an example that uses the except keyword.
number = 5 try: result = number/0 print(result) except: print('Divide by zero exception')
Divide by zero exception
Also Read: How To Display A Calendar In Python
The finally keyword in Python is used along with the try-except block, and the block of code present in the final block will execute if the try block raises an error.
number = 5 try: result = number/0 print(result) except: print('Divide by zero exception') finally: print('finally block always executes')
Divide by zero exception finally block always executes
Also Read: How To Sort a List of Tuples in Python
The False keyword is a boolean value that may come from a comparison operation. Let’s look into a simple example program that returns a boolean False value.
for keyword is used to create a loop, it is used to iterate the items over a list, tuple, etc. Let’s look into an example program of a for loop.
listofNumbers=[1,2,3,4,5] for item in listofNumbers: print(item)
1 2 3 4 5
Also Read: How to Create Python Empty Set
from keyword is used to import a specific section from the whole module. Let’s look into an example program of importing a specific section from a whole module using from keyword.
from math import pi print(pi)
Also Read: Python Matrix Using Numpy [With Examples]
global keyword is used to make variables global from a non-global scope. Using the global keyword, we can make variables in the function global and can be accessible across the code.
Let’s look into a sample program where variables are defined globally using the global keyword.
def globalScope(): global data data='global variable' globalScope() print(data)
Also Read: How To Create An Empty Dictionary in Python
if the keyword is used to create a conditional statement and executes the block of code in it if the condition is true.
Let’s look into an example program where if keyword is used.
number=10 if(number==10): print('Given number is 10')
Given number is 10
Also Read: How to Exit Python Program [4 Methods]
Import keyword in Python is used to import the required modules. Let’s look into the syntax of importing a module using an import statement.
import math # find square root value for 36 math.sqrt(36)
Also Read: How to Convert Python Tuples to Lists
in keyword is used to iterate over the items in a sequence in a for loop and to check whether an item is present in a sequence or not.
Sample program to iterate over items in a sequence.
# tuple sequence = (10,20,30) for i in sequence: print(i)
10 20 30
Sample program to check whether a particular item is present in a sequence or not.
# tuple sequence = (10,20,30) if 10 in sequence: print("Yes")
Also Read: Python For Loop Index With Examples
is keyword is used to check whether the two variables refer to the same object. It returns a boolean value. True if both variables refer to the same object. Let’s look into an example program where is keyword is used.
a = [1,2,3] b = a c = [1,2,3] print(a is b) print(a is c)
lambda keyword is used to create small functions. This is one of the ways of creating functions in Python. It takes any number of arguments but consists of only one expression. It evaluates the expression and returns the result.
Here is an example program where the lambda keyword is used to define a simple function.
# lambda function greaterthan10 = lambda number : number>10 print(greaterthan10(11))
the nonlocal keyword is mainly used in nested functions while working with variables. In nested functions, the nonlocal keyword helps to reference a variable in the parent function.
For better understanding, let’s look into two sample programs, one without the nonlocal keyword and the other with the nonlocal keyword.
Code without nonlocal:
# parent function def parentFunction(): str = 'Programming Tutorials' # child function def childFunction(): str='CodeItBro Programming Tutorials' # function call childFunction() return str print(parentFunction())
Code with local:
# parent function def parentFunction(): str = 'Programming Tutorials' # child function def childFunction(): nonlocal str str ='CodeItBro Programming Tutorials' # function call childFunction() return str print(parentFunction())
CodeItBro Programming Tutorials
Explanation: Using nonlocal keywords helps access variables in the upper scope in nested functions. Here the parentFunction function can access the str variable in the childFunction function.
None keyword is used to assign a null value to a variable.
var = None print(var)
not keyword is a logical operator which simply reverses the boolean value.
bool = True print(not bool)
Also Read: How To Automate Google Search With Python
or keyword is a logical operator used to combine conditional statements. It returns true if any of the conditional statements are true.
number = 2 if(number==2 or number==22): print('Condition Satisfied') else: print('Not satisfied')
Generally, empty code is not allowed in if statements, inside loops, functions, class definitions, etc. It leads to unExpected EOF error. So when programmers want to define a piece of code for future purposes, then the pass keyword can be used inside if, loops, function, etc., to prevent error.
def function_for_future(): pass function_for_future()
Note: Execution of this code will not give any result. But the advantage is unExpected EOF errors can be prevented during the cases when empty code is not allowed.
raise keyword is used to raise an Exception. The advantage of the raise keyword is we can specify the exception type and text to be displayed for that exception.
age = 17 if age<18: raise Exception('Not eligible to vote')
Exception Traceback (most recent call last) <ipython-input-10-3f8f1789c317> in <module> 2 3 if age<18: ----> 4 raise Exception('Not eligible to vote')
Also Read: 10 Best Udemy Python Courses for Beginners
The return keyword is used to return a value from the function. It also helps to exit from the function along with returning a value.
def demoFunction(): return 'Some value' print(demoFunction())
Also Read: 35 Funny And Best Python Programming Memes
True is a boolean value that may result from a comparison operation. Let’s look into a simple example program that returns a boolean True value.
try keyword is used along with except block. The try block defines the block of code, and if it contains any error respective/following except block will execute else block of code inside the try will execute without any interruption.
number = 5 try: result = number/0 print(result) except: print('Divide by zero exception')
Divide by zero exception
Also Read: How To Create Keylogger In Python
with keyword is used in exception handling to make code readable and cleaner. Let’s look into an example program where with keyword is used.
with open('demofile.txt', 'w') as file: file.write('CodeitBro')
Explanation: With keyword increases the code readability and decreases the lines of code. In this case, we didn’t specify the line of code to close the file but with keyword ensures proper acquisition and release of resources, thereby automatically closing the file.
Also Read: 7 Best Python IDE for Windows [Code Editors]
while keyword is used to create a loop. The interpreter executes the statements inside until the condition in a while gets failed.
number = 3 while(number!=0): print(number) number=number-1
3 2 1
In Python, the yield keyword is used to return a value from a function without destroying the state of variables, and execution starts from the last yield statement. The advantage of yield is it reduces the execution time of a program.
To better understand, let’s look into an example program where the yield keyword is used.
def double_the_number(): start = 1 # An infinite loop to double the numbers while 1: # execution starting point from 2nd iteration yield start+start start=start+1 for doubled_number in double_the_number(): print(doubled_number) # stops the infinite loop in the above function when returned number is >=10 if doubled_number>=10: break
2 4 6 8 10
Python-reserved words or keywords are unique words reserved for internal use, and programmers can’t use them as variables name in their programs. We hope you are now familiar with all Python keywords and how to use them in your programs. Stay tuned for more such articles, and subscribe to our newsletter to get them straight to your inbox.