Keywords in Python are unique reserved words that Python reserves for defining the syntax and structure of Python language.
We can’t use these keywords as an ordinary identifier in a Python program while naming variables, functions, objects, classes, and similar items.
There are 35 keywords in Python 3.10.6 version and this number may vary with different versions.
Therefore, you should avoid using these 35 keywords as identifiers to avoid errors or exceptions.
List of Reserved Keyword in Python Language
To retrieve the keywords in Python, write the following code at the prompt. All keywords except True, False, and None are in the lowercase letter.
Program code:
import keyword print(keyword.kwlist)
Output: ['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']
Table: Python Keywords
False | None | True | and |
as | assert | async | await |
break | class | continue | def |
elif | else | except | finally |
for | from | global | if |
import | in | is | lambda |
nonlocal | not | or | pass |
raise | return | try | while |
with | yield | del |
Description of Keywords in Python with Examples
a) True and False
True: This keyword represents a true boolean value. If a statement is true, Python interpreter returns a “True” value. Consider the following example code below.
print( 5 == 5 ) print( 10 > 9 ) print( True or False ) print( 9 <= 28 )
Output: True True True True
Since all statements in the above code are true, the interpreter returns True value. In Python, the boolean value “True” is equivalent to 1. Consider the following code to understand this statement.
print( True == 1 ) print( True + True + True)
Output: True 3
False: This keyword represents a false boolean value. If a statement is false, interpreter returns “False” value. Consider the following example code below.
print(10 > 20) print(50 <= 30) print(False == 1) print(False == 0) print(False + False + 1)
Output: False False False True 1
Since the first, second, and third statements are false, interpreter returns “False” boolean value. While the fourth statement is true, the result of comparison is “True” value. In Python, False is equivalent to 0 value, the last statement is 1 because 0 + 0 + 1 = 1.
Note that both “True” and “False” boolean values are the results of comparison operations or logical (Boolean) operations in Python.
None Keyword
This is a special constant in Python used to represent a null value or void (that means nothing). It has own data type. We consider “None” as nil, null, or undefined in different programming languages.
None is not equivalent to False, 0, or empty string, etc. If we compare “None” to anything other than “None” will always return False. Consider the below code to understand better.
print(None == False) print( None == 0 ) print( None == " " )
Output: False False False
In other programming language like Java, it is “null” object. But in Python, it is “None” object. We can assign None to any variable, but it is not possible to create multiple None type objects.
All variables whose values are None, are equal to each other. For example:
A = None B = None C = None print( A == B ) print( B == C ) print( A == C )
Output: True True True
Python Operator Keywords – and, or, not, in, is
a) and: It is a logical operator in Python that returns True value only if both operands on left-hand and right-hand sides are true. The truth table for and operator is as follows:
A | B | A and B |
---|---|---|
True | True | True |
True | False | False |
False | True | False |
False | False | False |
Consider the following example code below:
print(True and True) print(True and False and True) print(True and 1)
Output: True False 1
b) or: It is a logical operator in Python that returns “True” value if any of the operands are True. The truth table for or operator is as follows:
A | B | A or B |
---|---|---|
True | True | True |
True | False | True |
False | True | True |
False | False | False |
The following example code demonstrates the truth table.
print(True or True) print(False or False or True) print(True or False) print(True or 1)
Output: True True True True
c) not: This is a logical operator that inverts the truth value. The truth table for not operator is as follows:
A | not A |
---|---|
True | False |
False | True |
Let’s take an example based on not keyword.
print(not True) print(not False)
Output: False True
d) in: This is an operator used to check if a value exists in a sequence or not. It evaluates True if the value is present in the sequence otherwise; it returns False. Consider the following example code to understand better.
num = [10, 20, 30, 40, 50] print(50 in num) print(15 in num)
Output: True False
Another use of in keyword is to traverse over a sequence in a for loop. Look at the following example.
for i in 'keyword': print(i)
Output: k e y w o r d
e) is: This keyword is an operator used to test object identity. It returns True if both objects point to the same memory location, i.e. if two variables point to the same object.
If both objects are not the same, it returns False. Let’s take an example based on in keyword.
print( True is True ) print( False is True ) print( None is None ) print((2 + 4) is (3 * 2))
Output: True False True True
In Python, there is only one instance of True, False and None, so they are the same.
A blank list or dictionary is equivalent to another blank one. However, they are not identical objects or entities since Python store separately them in memory.
This is because both list and dictionary are mutable (changeable). Let’s take an example based on it.
print( [ ] == [ ] ) print( [ ] is [ ] ) print( { } == { } ) print( { } is { } )
Output: True False True False
Unlike list and dictionary, string and tuple are immutable (unchangeable, i.e. value cannot be modified once initialized). As a result, two equal strings or tuples are also identical as well. They point to the same memory location. Let’s take an example of it.
print( ' ' == ' ' ) print( ' ' is ' ' ) print( () == () ) print( () is () )
Output: True True True True
Python Iteration Keywords – for, while, break, continue
a) for: We use this keyword for looping. Generally, we use “for loop” in the program when we know exactly how many times we want to run a block of code.
Consider the following simple example below, the code prints “I live in Dhanbad” three times. Write the code in the Python editor and run it.
for count in range(1, 4): print("Scientech Easy, Dhanbad")
Output: Scientech Easy, Dhanbad Scientech Easy, Dhanbad Scientech Easy, Dhanbad
b) while: We use while keyword for looping in Python. A statement or group of statements inside a while loop continue to execute until the test condition for the while loop evaluates to False or encounters a break statement. Following example code shows this.
count = 0 while(count < 3): print("The current count is: ", count) count = count + 1 print("While loop ended!")
Output: The current count is: 0 The current count is: 1 The current count is: 2 While loop ended!
c) break: The break keyword in Python is used to end the loop statement and transfer the control of execution to the statement following immediately after the end of loop. Look at the following example code.
for i in range(1, 5): if i == 3: break print(i)
Output: 1 2
d) continue: This is another useful keyword for loops in Python. When we use continue keyword, the rest of the loop after the keyword is skipped for that iteration and immediately re-evaluates its condition prior to reiterating the loop. Let’s take an example that will make it clear.
for i in range(1, 6): if i == 4: continue print(i)
Output: 1 2 3 5
Python Conditional keywords – if, else, and elif
We use if, else, and elif keywords for conditional branching or decision making in Python.
When we want to evaluate a certain test condition and execute a block of code only if the condition is true, then we use if and elif. elif is the abbreviation of “else if”.
else is the block that executes if the condition is false. It will be more clear with the following example code:
i = 10 if (i == 5): print ("Hello") elif (i == 10): print ("Python keywords") else: print ("Hello Python")
Output: Python keywords
def keyword
We use def keyword for declaring a user-defined function in Python. A user-defined function is a block of code that performs together some specific tasks. An example code is as follows:
# Declaring a user-defined function. def func(): print("Inside Function") func()
Output: Inside Function
Python Return Keywords – Return, and Yield
a) return: We use the return keyword inside a user-defined function to exit it and return a value. If we do not return a value explicitly, the interpreter automatically returns None by default. A below example will make it clearer.
# Declaring user-defined functions with return keyword. def func_return(): x = 20 return x def func_no_return(): y = 50 print(func_return()) print(func_no_return())
Output: 20 None
b) yield: We use yield keyword inside a function like a return statement but yield returns a generator object to the caller rather than a data value. An example code is as:
# Yield Keyword def func(): x = 0 for i in range(5): x += i yield x for i in func(): print(i)
Output: 0 1 3 6 10
class Keyword
We use class keyword to declare a user-defined class in Python. In any programming language, a class is a collection of as many as objects.
A class is basically a user-defined data type that consists of data members, functions, etc. According to OOPs, a class is a template of an object that provides state and behaviour for an object.
We can define a class anywhere in a Python program. But it is a good practice to declare a single class in a module. An example of the declaration of a class in Python program is as:
class ClassExample: def func1(parameters): . . . . def func2(parameters): . . . .
with Keyword
We use with keyword in Python to wrap the execution of a block of code within methods defined by the context manager. Programmer is avoiding to use with keyword much in day to day programming. Here is an example of using with keyword.
with open('myfile.txt', 'w') as file: file.write('Scientech Easy!')
In this example, we have written the text Scientech Easy! to the file myfile.txt.
as Keyword
We use “as” keyword in Python to create an alias (i.e. user-defined name) while importing a module. That is, as keyword is used to give a different user-defined name to a module while importing it.
For instance, Python has a standard module named math. Suppose we want to find out the value of cos(0). We can do it using the following code:
import math as x print(x.cos(0))
Output: 1.0
In this example, we have imported a module named math by giving it a user-defined name x. Now we can point to the math module using this name x. Using this name x, we have calculated the value of cos(0) and got the result 1.0.
pass Keyword
This keyword simply represents a null statement in Python. When interpreter encounters pass keyword, then nothing happens. We normally use it as a placeholder to prevent indentation error and creating empty function or class. Look at the below example.
def func(): pass class A: pass
lambda Keyword
We use lambda keyword in Python to create a function with no name and return statement. It comprises only expression for evaluation. For example:
# Lambda keyword cube = lambda x: x * x * x print(cube(7))
Output: 343
Here, we have created an anonymous function (with no name) that calculates the cube of value, using the lambda statement.
import Keyword
The import keyword is used to import all attributes of a module in the current program. Let’s take an example of it.
import math print(math.sqrt(25))
Output: 5.0
from Keyword
Generally, we use from keyword with the import statement to include only a specific attribute from the module. Let’s take an example based on it.
from math import sqrt print(sqrt(625))
Output: 25.0
del Keyword
Everything is an object in the real world of Python. We use del keyword to delete a reference to an object. We can delete any variable or list value from memory location using del keyword. For example:
my_var1 = 200 my_var2 = "Scientech Easy" # check if my_var1 and my_var2 exists. print(my_var1) print(my_var2) # delete both the variables. del my_var1 del my_var2 # check if my_var1 and my_var2 exists print(my_var1) print(my_var2)
Output: 200 Scientech Easy NameError: name 'my_var1' is not defined
global Keyword
In Python, global keyword allows the programmer to declare a global variable outside the function globally. A variable defined outside the function or in global scope is called global variable.
It is necessary to write the global keyword to use global variable inside the function. But, there is no need to use global keyword outside the function. The following example code will clarify more it.
g_var = 50 def func_read(): print(g_var) def func_write(): global g_var g_var = 100 func_read() func_write() func_read()
Output: 50 100
In this example, the func_read() function is just reading the value of g_var variable. Therefore, we do not need to declare it as global.
But the func_write() function is modifying the value of the variable, so we need to declare the variable with a global keyword. You can observe in the output that the modification took place (50 is changed to 100).
nonlocal Keyword
The nonlocal keyword functions similarly to the global keyword. Generally, we use nonlocal keyword to declare a variable inside a nested function (function inside a function) which is not local to it.
It means that the scope lies in the outer inclosing function. To modify the value of a nonlocal variable inside a nested function, we must declare it with a nonlocal keyword.
Else, a local variable with that name will define inside the nested function. An example code below will demonstrate it.
def outer_func(): x = 50 def inner_func(): nonlocal x x = 100 print("Inner function: ",x) inner_func() print("Outer function: ",x) outer_func()
Output: Inner function: 100 Outer function: 100
In this example, the inner_func() is nested inside the outer_func(). The variable x is in the outer_func(). So, if we modify it in the inner_func(), we must declare it as nonlocal. Note that here, x is not a global variable.
You can observe in the output that we have successfully modified the value of variable inside the nested inner_func() function. The outcome of not using the nonlocal keyword is as:
def outer_func(): x = 50 def inner_func(): x = 100 print("Inner function: ",x) inner_func() print("Outer function: ",x) outer_func()
Output: Inner function: 100 Outer function: 50
Python Exception Handling Keywords – try, except, raise, and finally
Python allows to programmer to handle exception or errors in the code using try-except keywords. We place the code inside the try block.
If there is an error inside try block, except block is executed. The except block executes when an exception occurs inside the try block.
The finally block always gets executed whether or not an exception occurs inside the try block. We can raise an exception explicitly with the raise keyword in Python. Let’s take an example of it.
# initializing the value of variables. x = 10 y = 0 # No exception raised in try block try: z = x // y # raises divide by zero exception. print(z) # handles zero division exception except ZeroDivisionError: print("Cannot divide by zero") finally: # this block always gets executed regardless of exception produced. print('finally block always gets executed')
Output: Cannot divide by zero finally block always gets executed
assert Keyword
In Python, we use assert keyword for debugging purpose. Sometimes, we need to debug the internal state of some assumptions.
In this case, assert keyword helps us to find bugs more conveniently. assert is followed by a condition. If the condition evaluates to true, nothing happens.
But if the condition evaluates to false, AssertionError is raised. Consider the following example code below that will clear more.
x = 10 assert x >= 10 assert x < 10
Output: Traceback (most recent call last): File "string", line 3, in assert x < 10 AssertionError
We can also pass an error message with assert to be displayed with AssertionError. Look at the example below.
x = 10 assert x < 10, "x is not less than 10"
Output: Traceback (most recent call last): File "string", line 2, in assert x < 10, "x is not less than 10" AssertionError: x is not less than 10
In this tutorial, we have covered about reserved keyword in Python with lots of example program. Hope that you will have understood the basic points of reserved keywords and practiced all example programs.
Thanks for reading!!!
Next ⇒ Identifiers in Python⇐ Prev Next ⇒