Python Introduction

List of Keywords in Python Programming

Reserved words are present in every programming language. Be it Java or Python, each programming language has a set of reserved keywords. These words are also known as keywords. They convey a specific message. Additionally, there are certain restrictions around their usage. Let us learn python keywords in detail. 

Python Keywords

Python is no exception to the above rule. Keywords form a fundamental part of every Python program. Every reserved word has a specific purpose. A programmer can’t use the Python keywords for any other purpose apart from the predefined use. An important point to note is that programmers are not required to be imported. They are always available to the programmers. A programmer can get a list of the keywords by following the below steps –

Syntax:  Type in help followed by keywords in parenthesis.

>>> help(“keywords”)

Output: Below will be the output that you will be able to see on your screen

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

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

There are 35 Python keywords as of Python 3.8.

Point to Note:

  1. The Python Keywords should not be confused with the built-in functions provided by Python. Although the built-in functions are also always available, there are fewer restrictions on their usage. For example, you will get a “SyntaxError” if you try assigning a keyword to a variable. However, you will not get any such error if you try to assign the in-built functions to a variable. As a good practice, programmers usually avoid assigning variables to built-in functions.
  2. It is critical to understand that the keywords are case-sensitive. Hence, ‘break’ will not be the same as ‘Break’. 

Another common point of confusion is between keywords and identifiers. To understand the difference, we must be aware of what an identifier is. An identifier is a name given to various entities like functions,  classes, and variables. Identifiers help a programmer to distinguish between entities. Below are the differences between Python keywords and identifiers-

Basis for comparison Keyword  Identifier
Basic A keyword refers to a predefined word that python reserves for working programs that have a specific meaning. A programmer can’t use a keyword anywhere and everywhere. There are applicable restrictions for the usage of keywords. Python Identifiers are the different values that a programmer can use to define various variables, integers, functions, and classes. 
Usage A keyword specifies the type of entity. A programmer can use an identifier to identify a single entity (a variable, a class, or a function). 
Case of the starting letter All the keywords apart from ‘True’, ‘False’, and ‘None’ start in lowercase letters. The first character of an identifier can be a lowercase letter or an uppercase letter. However, a digit can not be the starting point for an identifier.
Case of the word Usually, keywords are in lower case. A variable can be in uppercase or lowercase letters.
Composition Python Keywords comprise alphabetical characters. An identifier can consist of alphabets, numbers, and underscore. 
Usage of special characters A keyword does not make use of special characters. Except for underscore (‘_’), no other special character can be used in a Python identifier. Even punctuation marks can not be used.
Examples A few examples of commonly used Python keywords are: True, False, else, import, break, if, finally, is, and global. A few examples of identifiers are testing, sq4 sides, area_rectangle, sumNumbers, etc. 

Now that we have understood the difference between a Python Keyword and an Identifier, we can understand the usage of each of the keywords.

None:  

A null object or variable can be denoted using the none keyword. In the Python programming language, the none keyword itself is an object. Simply put, it is a data type of the NoneType class. Hence, it is not possible to create another NoneType class. A programmer can assign the null object to any variable. All objects that are assigned the None point will refer to the same object. A new instance of None will not be created every time we assign it to a new variable. 

Syntax: The syntax to use the above keyword is –

None

Points to Note: 

  • Both the == operator and the is operator is supported by the none keyword
  • None doesn’t mean 0. It means NULL. Both aren’t the same.
  • The False keyword and the none keyword aren’t the same things.
  • If you compare none with anything else, the statement will always return a False. It returns a True only if none is being compared with another none.
  • None doesn’t denote an empty string.

Examples

  1. A program to demonstrate the use of the is Python keyword to check if a variable is none. 

                    

#declaring a variable as None

var1 = none

 

If var1 is none:

  print(“It is a none variable”)

else:

print(“ It is not a none variable”)


                
Output: On running the above program, you get the below output-

It is a none variable.

As per the above program, variable var1 was assigned none. Hence, the if condition returns a True value, and the subsequent section is executed.

  1. A program to demonstrate the use of the == Python keyword to check if a variable is none. 
                    

#declaring a variable as None

var1 = none

 

If var1 == none: #to check if the variable is none

  print(“It is a none variable”)

else:

print(“ It is not a none variable”)

Output: On running the above program, you get the below output-

It is a none variable.

break:

While programming, we might encounter a situation where we have to exit a loop completely if a specific condition is fulfilled. It is in such scenarios that the Python keyword break proves to be helpful. The break statement helps a programmer to have control over the loops.

The break statement will terminate the current loop and start the execution from the next statement. The break statement can be used with while loops and for loops.

except

The except keywords allow us to handle an exception that we might encounter in the try block. The try block checks the program for errors. On the other hand, the except block will execute only if Python encounters an exception in the try block. A try block can have multiple except clauses.

Dummy Syntax:

try:

                    

#the code that you need to check for an error

except:

#this part will execute only if any error is encountered in the try block

Initially, the code section between try and except is executed. If there is no exception, the except block does not run. However, if an exception occurs, the except block will run.

in

There are two uses of the in Python keyword. Firstly, it can check if a sequence (string, range, list) contains a particular value. Secondly, it can also serve as a sequence iteration in a For loop.

Syntax: Below is a program to demonstrate the use of the in keyword.

                    

occupation = [“Doctor”, “Engineer”, “Analyst”]



for x in occupation:

print(x) 

Output: Below is the output for the above code segment

raise

A programmer can use the raise keyword in Python to raise an exception. You get the opportunity to decide what type of error to raise. You can also modify the error message that will be displayed to the user. 

Syntax: A code block to understand the use of the raise keyword-

                    

var = “testing”



if not type(var) is int:

raise typerror( “ You can enter only integers”)

Output: Since the variable is not an integer, the user will see the error message “you can enter only integers”.

False

We can compare the False Python keyword to a boolean value. A comparison will result in a boolean value. False is comparable to 0 (similarly, True is comparable 1)

Example: The below statement shows the syntax to use the False keyword

print (3 > 6)

Output:

As the above statement is not true, hence the statement returns a False value. Below are a few more statements that will return false-

print(1 == 2)

print( 3 < 2) 

await

The await keyword enables the program to wait for the duration which the programmer mentions in the statement. It helps a programmer to write concurrent pieces of code in Python. 

Syntax: The below statement will make the program wait for one second before executing subsequent codes.

await.asyncio.sleep(1)

import

The import keyword helps us to import various modules in the namespace we are working on.

Example: The below statement will import the math module into our program. We can use various functions like sin() and cos() after importing the module.

pass

The pass statement is more like a placeholder. It is similar to a null statement where nothing will happen if it is executed. It can be used in scenarios where we have a function that is present but is not implemented. However, we might want to implement it in the future.

 else

The else statement aids conditional branching and helps in decision-making for the programmers. In case, the prior if and elif statements are not satisfied, the flow of control will move to the else statement.

 and

The and keyword is one of the logical operators that programmers can use in Python. The working of the keyword is similar to working in other programming languages. The and-operator will return a True value only if both the operands in the statement have a true value. Even if one of the operands is false, the value returned by the statement will be False.

Syntax: The below statement shows the use of the or keyword

>>> True and False

Output: The out of the above will be False as one of the statements is False.

Output: The output of the above statement will be False as both operands are False.

Output: The output of the above statement will be True as both operands are True.

 continue 

We use continue inside for or while loops to end a current iteration and continue to the next iteration. 

Example: for text in range(2,10):

                 

                    

   if i == 5:

                          continue

                      print(text)

Output: The output would be the numbers from 2 to 10 except 5 because when the condition is met, the iteration is skipped.

 lambda

We can use lambda to create a function without a name. The function will not contain a return statement. It comprises a expression that will be returned after evaluation.

 try

The try keyword along with the catch keyword is used to catch exceptions in a Python program.  

 True

We can compare the True Python keyword to a boolean value. A comparison will result in a boolean value. True is comparable to 1 (similarly, False is comparable to 0)

Example: The below statement shows the syntax to display the True keyword

print (9 > 6)

Output: True

As the above statement is true, hence the statement returns a True value. Below are a few more statements that will return true-

 

print(1 == 1)

print( 3 < 8) 

 Class

Since Python is an object-oriented language, everything is an object including a class. It is a group of python attributes and methods which is used to collect objects such as functions. We can define a class anywhere but the best way is to define one class in a module.

 Example: class MyClass:

                                 

                    

def myfunc(x):

                                       ….

                                   def myfunc2(y):

                                       ….

 Finally

When there is a situation when a method has to handle an exception, finally keyword is used and it is always executed after the try and except blocks. It makes sure that a code is executed even if we have an unhandled exception, like closing a file or a network, etc.

Example: try:

        Some Code… 

 

except:

        optional block

        Handling of exception (if required)

 

finally:

       Some code …..(always executed) 

 is 

The is keyword helps us to test if the two operands are referring to the same object. It will return True if both the operands are referring to the same object. Else, it will return a false.

 return 

We can use the return statement if we want to exit a function and return a value along with it. 

 as 

We can use the above Python keyword when we want to import a module and give it a different name. For example, Python has standard module math. We can import it and give it an alias of our own choice using the as keyword.

 def 

The def keyword is used to define a user-defined function.

Syntax: 

 

def name_of_function(parameters)

 from 

The from keyword helps us to import various modules in the namespace we are working on. If we want to import specific functions from a module, we can use the from keyword. 

 

Example: In the below statement, we are being specific to call the cos function from the math module. Thus, we are not importing the entire math module

from math import cos

 nonlocal

It is pretty similar to the global keyword. The only difference is that nonlocal is used to denote that a variable within a nested function is not a local variable. In other words, the variable lies in the outer function. To modify the value of a non-local variable within a nested function, we need to use the Python Keyword nonlocal.

 while/for

The while/for keyword is used to run loops in Python. All the statements with the loop will keep on executing as long as the condition for the while loop or the for loop is getting satisfied. The moment the condition is false, the loop will break.

Example: Below is a program to print numbers in descending order using a while loop

                    

j = 4

while(j)

print(j)

j = j - 1

Output: The loop breaks the moment the value of j turns to zero. Hence, numbers greater than zero are printed.

4

3

2

1

python keywords

 async 

The async keyword helps a programmer to write concurrent pieces of code in Python. It is a part of Python’s asyncio library. The keyword defines that the functions can execute asynchronously. 

 elif

Similar to the else statement, even the elif statement aids conditional branching and helps in decision-making for the programmers. It is the short form for Else if. Hence, in case the if condition is not satisfied but the elif condition is satisfied, the code-block succeeding it will execute.

Example: Below is an example to help you understand the use of elif

d

                    

ef example(a):

if (a == 4)

print ( ‘four’)

elif(a == 5)

print (‘five’)


example(4)

example(5)

Output: In the first case, the if-condition is satisfied and hence the output is four. The elif section is not executed in this case.

However, in the second case, the if condition is not satisfied. Thus, the flow reaches the elif section. As the condition is satisfied, the output is five.

 

four

five

 If

The if statement aids conditional branching and helps in decision-making for the programmers. If we want to test a particular condition and execute a code-block only if the condition is true, we can use the if statement. If the condition returns a false value, the whole code-block will be skipped. 

Example: Below is an example to help you understand the use of if

                    

def example(a):

if (a == 2)

print ( ‘two’)

elif(a == 3)

print (‘three’)

example(2)

example(3)

Output: In the first case, the if condition is satisfied and hence the output is two. In the second case, the if condition is not satisfied. Thus, the output is three.

two

three

 not 

The not keyword is one of the three logical operators present in Python. The implementation of the not reserved word is similar to common programming languages like Java. The above operator will invert the value of the operand

Syntax: A statement to show the result of not-operator on the values-

 

>>> not False

 

Output: As the not operator inverts the operand, the output of the above statement will be True.

 

>>> not True

 

Output: As the not operator inverts the operand, the output of the above statement will be False.

 with 

The with keyword is one of the most significant keywords in Python. It allows the programmer to wrap up the execution of a  code block within the methods that the context manager defines. The context manager is the class that defines the exit and enter methods in Python. Using the with keyword ensures that the exit method is mandatorily called after a nested block is over. It is similar to the try-catch block that we have studied earlier.

Example:

with open(‘test.txt’, ‘w’) as my_file:

my_file.write(‘testing keywords’)

Output: As a result of the above statements, the text testing keywords will be written to file text.txt. The file object will have an exit method and an enter method defined within it. Initially, the enter method is called. Following that, the section after the with Python keyword is executed. Finally, the exit method runs to close the file stream.

 assert 

The assert keyword is helpful in the debugging process. While writing a piece of code, the programmers might want to check the internal states or if their assumptions are true. The above keyword helps us do that. Thus, the process of finding and resolving bugs becomes easier. A condition will always follow the assert keyword. Nothing will happen if the condition is true. But if the condition is false, an AssertionError will be raised. To ease the process, we can add a message to be displayed along with an AssertionError.

 del

The use of the del Python keyword is to delete the reference of any object in Python. As everything in Python is an object, programmers can use the above keyword to delete the reference of any variable. The del keyword has the ability to items from a list and a dictionary as well. 

Example:

                    

def example(a):

if (a == 2)

print ( ‘two’)

elif(a == 3)

print (‘three’)

Output: The output of the above statements will be the first character and the third character of the list. The second character was deleted using the del keyword

[‘j’ , ‘n’]

 global 

The global keyword indicates that the variable before which it is written is available globally. In other words, the programmers will be able to access the variable anywhere in the program. A point to keep in mind is that to read the value of various global variables, it is not mandatory to define them as global. It is implied that the variable is global. However, if we have to make changes to the value of a global variable, it is compulsory to declare the variable as global. If we miss doing so, a local variable with an exact similar name will be created. Hence, the modified value will not pass to the global variable.

Example: Below is an example to show what will happen if we miss adding the global keyword while we are modifying the value of a variable within a function.

                    

globvar = 10

def func1():

print (globvar)

def write():

global globvar

globvar = 5

def write1():

globvar = 15



func1()

write()

func1()

write1()

func1()

Output:  Since the variable in the write1 function was declared without the global keyword, its value is linked to it locally. Hence we will get the output as 5 when we print the globvar. However, in the first case, global precedes the variable. Hence, the modified value is passed to the global variable. Thus, we will get five as the output in both cases.

10

5

5

Output: global

 

 or 

Or is a significant operator keyword that is used in Python. It is a keyword that is similar to other programming languages. An or keyword will return a True value even if one of the operands is True.

Syntax: The below statement shows the use of the or keyword

>>> True or False

Output: The out of the above will be True as one of the statements is True.

>>> False or False

Output: The output of the above statement will be false as both operands are false.

 yield 

It is one of the most useful Python Keywords. It gives you the privilege to come out from a function without destroying the various states of the local variables. Whenever the function is called again, the execution of the function starts from the previous yield statement. A generator is any function that contains a yield statement. Not many programmers are aware of the power of the yield keyword. However, it is very useful. 

Syntax: A sample program to demonstrate the working of the yield keyword-

                    

#A Python code to demonstrate the yield keyword

#a generator to some print even numbers 



Def print_ev(test_l):



for j in test_l:

        if j % 2 == 0:

            yield j

  

# initializing the list 

test_l = [1, 2, 5, 6, 7]

  

# printing initial list

print ("The given original list is : " + str(test_l))

  

# printing even numbers 

print ("The even numbers in list are : ", end = " ")

for k in print_even(test_list):

    print (k, end = " ")

Output: The above program results in the below output

The given original list is : [1, 2, 5, 6, 7]

The even numbers in the list are: 2, 6

It is one of the most useful Python Keywords. It gives you the privilege to come 

FAQs on Keywords in Python

Q: What are keywords in Python along with an example?

A: Python reserves a certain set of keywords for various internal operations. These words are also known as Python Keywords. These words cannot be used for naming variables, functions, or classes. There are certain restrictions on the usage of these keywords. A few common keywords are break, global, yield, else, and raise.

Q: How do I get a list of keywords in Python?

A: A programmer can get a list of the keywords by following the below steps –

Syntax:  Type in help followed by keywords in parenthesis as shown below.

>>> help(“keywords”)

Output: Below will be the output that you will be able to see on your screen

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

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

Q: How do you use any keyword in Python?

A: You can’t use a Python keyword to name a variable or any other identifier. The syntax for each keyword depends on the purpose of the keyword. Hence, the syntax will be different for different keywords.

Q: How many keywords are there in Python 3?

A: There were 33 keywords in Python 3.7. However, the number increased to 35 in Python 3.8. Hence, we can see that the number of keywords in Python is not constant. It might vary from version to version. Refer to the table above to understand the various keywords that you can use while programming in Python.

Share with friends

Customize your course in 30 seconds

Which class are you in?
5th
6th
7th
8th
9th
10th
11th
12th
Get ready for all-new Live Classes!
Now learn Live with India's best teachers. Join courses with the best schedule and enjoy fun and interactive classes.
tutor
tutor
Ashhar Firdausi
IIT Roorkee
Biology
tutor
tutor
Dr. Nazma Shaik
VTU
Chemistry
tutor
tutor
Gaurav Tiwari
APJAKTU
Physics
Get Started

Leave a Reply

Your email address will not be published. Required fields are marked *

Download the App

Watch lectures, practise questions and take tests on the go.

Customize your course in 30 seconds

No thanks.