Wednesday, October 4, 2023
HomeProgrammingPythonPython Reserved Words List With Definitions and Examples

Python Reserved Words List With Definitions and Examples

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 ReadHow 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.

  1. and
  2. as
  3. assert
  4. break
  5. class
  6. continue
  7. def
  8. del
  9. elif
  10. else
  11. except
  12. finally
  13. False
  14. for
  15. from
  16. global
  17. if
  18. import
  19. in
  20. is
  21. lambda
  22. nonlocal
  23. None
  24. not
  25. or
  26. pass
  27. raise
  28. return
  29. True
  30. try
  31. with
  32. while
  33. yield

Also ReadHow To Copy List in Python

All Python Reversed Words or Keywords With Definitions and Examples

python reserved words list

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.

Code:

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")

Output:

Given number is greater than 10

Also Read: 10 Best Programming Apps To Learn Python

2. as

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.

Code:

# create an alias word for numpy
import numpy as np

# create a numpy array
strArray=np.array(['Code','IT','Bro'])

print(strArray)

Output:

['Code' 'IT' 'Bro']

Also ReadPython Program To Reverse A Number

3. assert

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.

Code:

number = 1

# assert when condition is true
assert number==1

# assert when condition is false
assert number==10

Output:

AssertionError                            Traceback (most recent call last)
<ipython-input-3-3256f06e4462> in <module>
      5 
      6 # assert when condition is false
----> 7 assert number==10

AssertionError:

Also ReadPython Program to Find Sum of Digits [5 Methods]

4. break

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.

Code:

for i in range(0,5):
    if i==3:
        break
    print(i)
    i=i+1

Output:

0
1
2

Also ReadPython Program To Check If A Number Is Perfect Square

5. class

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.

Code:

class Car:
    company='TATA'
    model='punch'
    price=948900

Also ReadIncrement and Decrement Operators in Python

6. continue

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.

Code:

# skips 3rd iteration
for i in range(1,5):
    if i==3:
        continue
    print(i,'iteration')
    i=i+1

Output:

1 iteration
2 iteration
4 iteration

Also ReadPython Dictionary Length [How To Get Length]

7. def

def keyword is used to define the function in Python. The syntax to define a function using the def keyword is given below.

def functionName():
#body

The sample program uses the def keyword to define a function.

Code:

def sampleFunction():
    print('Demo function')

sampleFunction()

Output:

Demo function

Also ReadHow To Concatenate Arrays in Python [With Examples]

8. del

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.

Code:

stringobj='Hello World'
print(stringobj)

del stringobj
print(stringobj)

Output:

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 ReadWhat Does The Python Percent Sign Mean?

9. elif

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.

Code:

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')

Output:

A Grade

Also ReadHow to Create an Empty Array In Python

10. else

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.

Code:

score=84

if(score>40):
    print('Pass')
else:
    print('Fail')

Output:

Pass

Also ReadWhat Is Python Used For? Applications of Python

11. except

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.

Code:

number = 5
try:
    result = number/0
    print(result)
except:
    print('Divide by zero exception')

Output:

Divide by zero exception

Also ReadHow To Display A Calendar In Python

12. finally

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.

Code:

number = 5
try:
    result = number/0
    print(result)
except:
    print('Divide by zero exception')
finally:
    print('finally block always executes')

Output:

Divide by zero exception
finally block always executes

Also ReadHow To Sort a List of Tuples in Python

13. False

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.

Code:

print(1==2)

Output:

False

Also ReadArithmetic Operators in Python [With Examples]

14. for

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.

Code:

listofNumbers=[1,2,3,4,5]

for item in listofNumbers:
    print(item)

Output:

1
2
3
4
5

Also ReadHow to Create Python Empty Set

15. from

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.

Code:

from math import pi
print(pi)

Output:

3.141592653589793

Also ReadPython Matrix Using Numpy [With Examples]

16. global

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.

Code:

def globalScope():
    global data
    data='global variable'

globalScope()
print(data)

Output:

global variable

Also ReadHow To Create An Empty Dictionary in Python

17. if

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.

Code:

number=10
if(number==10):
    print('Given number is 10')

Output:

Given number is 10

Also ReadHow to Exit Python Program [4 Methods]

18. import

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 moduleName

Code:

import math
# find square root value for 36
math.sqrt(36)

Output:

6.0

Also ReadHow to Convert Python Tuples to Lists

19. in

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.

Code:

# tuple
sequence = (10,20,30)

for i in sequence:
    print(i)

Output:

10
20
30

Also ReadHow to Handle String Index Out of Range Error In Python

Sample program to check whether a particular item is present in a sequence or not.

Code:

# tuple
sequence = (10,20,30)

if 10 in sequence:
    print("Yes")

Output:

Yes.

Also ReadPython For Loop Index With Examples

20. is

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.

Code:

a = [1,2,3]
b = a
c = [1,2,3]
print(a is b)
print(a is c)

Output:

True
False

Also ReadHow to Reverse an Array In Python [Flip Array]

21. lambda

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.

Code:

# lambda function
greaterthan10 = lambda number : number>10

print(greaterthan10(11))

Output:

True

Also ReadHow to Check If Dict Has Key in Python [5 Methods]

22. nonlocal

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())

Output:

Programming Tutorials

Also ReadHow to Convert Binary to Decimal in Python [5 Methods]

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())

Output:

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.

Also ReadPython Program To Display Fibonacci Series Up To N Terms

23. None

None keyword is used to assign a null value to a variable.

Code:

var = None
print(var)

Output:

None

Also ReadPython Program To Display Multiplication Table of Any Number

24. not

not keyword is a logical operator which simply reverses the boolean value.

Code:

bool = True
print(not bool)

Output:

False

Also ReadHow To Automate Google Search With Python

25. or

or keyword is a logical operator used to combine conditional statements. It returns true if any of the conditional statements are true.

Code:

number = 2

if(number==2 or number==22):
    print('Condition Satisfied')
else:
    print('Not satisfied')

Output:

Condition Satisfied.

Also ReadPython Program To Check If a Number is Odd or Even

26. pass

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.

Code:

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.

Also ReadPython App Development Scope—Everything You Should Know

27. raise

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.

Code:

age = 17

if age<18:
    raise Exception('Not eligible to vote')

Output:

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 Read10 Best Udemy Python Courses for Beginners

28. return

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.

Code:

def demoFunction():
    return 'Some value'

print(demoFunction())

Output:

Some value

Also Read35 Funny And Best Python Programming Memes

29. True

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.

Code:

print(1==1)

Output:

True

Also ReadHow To Use Python For Browser Games Development?

30. try

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.

Code:

number = 5
try:
    result = number/0
    print(result)
except:
    print('Divide by zero exception')

Output:

Divide by zero exception

Also ReadHow To Create Keylogger In Python

31. with

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.

Code:

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 Read7 Best Python IDE for Windows [Code Editors]

32. while

while keyword is used to create a loop. The interpreter executes the statements inside until the condition in a while gets failed.

Code:

number = 3
while(number!=0):
    print(number)
    number=number-1

Output:

3
2
1

Also ReadSending Emails Using Python With Image And PDF Attachments

33. yield

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.

Code:

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

Output:

2
4
6
8
10

Also ReadLearn Python Online With These 12 Best Free Websites

Summary

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.

Himanshu Tyagi
Himanshu Tyagi
Hello Friends! I am Himanshu, a hobbyist programmer, tech enthusiast, and digital content creator. Founder Cool SaaS Hunter. With CodeItBro, my mission is to promote coding and help people from non-tech backgrounds to learn this modern-age skill!
RELATED ARTICLES