Python Keywords
Python Keywords
Keywords are the reserved words that have special meanings to the compiler. They cannot be used as a variable. Keywords are the part of the syntax, for example:
return (a+b)
Here return is a keyword, whereas, a and b are variables.
Below is the list of all keywords used in Python:
and | else | lambda |
or | except | None |
assert | finally | nonlocal |
break | try | pass |
continue | raise | global |
class | from | return |
def | import | False |
del | in | True |
if | is | for |
elif | not | while |
with | yield |
Descriptionof Python keywords
if
Python if statement is the simplest conditional statement. It is used to decide whether a block of the statement will be executed or not.
a = 20 if (a>15): print("I am bigger than 15")
Output:
I am bigger than 15
else
An else statement is associated with if statement. When if statement’s condition is false then else block is executed. The following example makes it clear:
a = 20 b = 30 if (a> b): print('a is greater than b') else: print('b is greater than a')
Output
b is greater than a
elif
The elif is short for else-if. It is used for checking multiple conditions, which means that if the previous condition is false than check for the next condition. For example:
a=10 b=10 if (a>b): print('a is smaller than b') elif (a == b): print(' a is equal to b') else: print('a is greater than b')
Output:
a is equal to b
True
True keyword is used to represent a boolean true. If the given statement is true then interpreter returns true. For example:
print(1==1)
Output:
True
False
False Keyword is used to represent a boolean false. If the given statement is false then interpreter returns false. For example:
print(1>1)
Output:
False
assert
The assert is a keyword which is used as a debugging tool.It helps in a smooth flow of code. It helps us to find bugs more conveniently
Assertions are mainly assumptions that a programmer knows andalways wants it to be true. Hence puts them in code so that failure of that statement doesn't allow the code to execute further.
a = 10 b = 0 print('a is dividing by Zero') assert b != 0 print(a / b)
Output:
a is dividing by Zero
Runtime Exception:
Traceback (most recent call last): File "/home/40545678b342ce3b70beb1224bed345f.py", line 4, in assert b != 0, "Divide by 0 error" AssertionError: Divide by 0 error
and
and, or, not are the logical operators in Python. In and operator, if both operands are true, then the condition will become true. For example:
a=100 if (a>90) and (a<101): print('Both conditions are true.a is ',a)
Output:
Both conditionsare true. a is 100
The Truth table of and operator is given below:
A | B | A and B |
True | True | True |
True | False | False |
False | False | False |
False | True | False |
or
or operator returns true if one of the statement is true
a=100 if (a>90) or (a>99): print('If anyone condition is true then a is’,a)
Output:
If anyone condition is true then a is 100
The truth table is following
A | B | A or B |
True | True | True |
True | False | True |
False | True | True |
False | False | False |
not
not operator returns true if given statement is false
a = 100 if(not(x>105)): print('a is', a)
Output:
a is 100
The truth table ofnot is given below:
A | Not A |
True | False |
False | True |
class
The class keyword is used to define a class in Python. Class is a collection of data (variables) and methods. The class can represent a real-world state. It is the main concept of OOPs (Object Oriented programming).
class Myclass: #Variables…….. def function_name(self): #statements………
del
The del keyword is used to delete the reference of the object.
a=5 del a print(a)
Output:

In the above code, variable a is no longerusedbecause the reference of the variable is deleted.
def
The def keyword is used to define a function. A function is used to divide our program into smaller and modularsub-parts. It provides reusability to our program. As programs grow larger, the function makes it more manageable.
def function_name(arguments): #function block
return
It is used inside the function to exit it and returns a value or none.
def add (a, b): sum=a+b return sum sum = sum (20,30) print ('The sum is ', sum)
Output:
The sum is 50
pass
The pass keyword is used when we want to execute nothing or create a placeholder for future code, if you declare an empty function or class, you will get an error without using pass statement.
class Myclass: pass def myfun(arguments): pass
try, except
Exceptions are the runtime errors. Few examples of exception are ValueError, ZeroDivisior, NameError, TypeError, etc. try-except blocks are used to handle exceptions in Python.
a = 0 try: b = 1/a except Exception as e: print(e)
Output:
division by zero
raise
The raise keyword allows to throws an exception at any time. For example:
a = 10 if (a>5): raise Exception('a should not be exceeded than 5')
Output:
Exception: a should not be exceeded than 5
finally
The finally block will always be executed no matter whethertry-expect block raises an error or not. For example:
try: a=0 b=20 v = b/a print(v) except Exception as e: print(e) finally: print('Finally Always executed')
Output:
division by zero Finally Always executed
import
The import keyword is used to import modules into the current namespace.
import datetime x = datetime.datetime.now() print(x)
Output:
2019-08-05 16:19:16.334428
from
The fromkeyword is used for a specific function or attributes into the current namespace.
from math import sqrt x = sqrt(16) print("The square root of 16 is ", x)
Output:
The square root of 16 is 4.0
as
as keyword is used to create an alias while importing a module. With the help ofas, we can provide a user-defined name while importing a module. For example: importing a Python module calendar using alias name as cal.
import calendar as cal print(cal.month_name[1])
Output:
January
for
for is a keyword that is used for looping or iterating over a sequence (dictionary, list, string, set or tuple).
With for loop we can execute a set of statement once for each item in iterator(list, tuple, set, etc).
names = ['Ajay','Himanshu','Abhay','Anubhav'] for i in names: print(i)
Output:
Ajay Himanshu Abhay Anubhav
while
A while loop is executed until the given condition evaluates to false or break statement is encountered. It is also used to make an infinite loop.
a=0 while(a<=5): a = a+1 print(a)
Output:
1 2 3 4 5
break
The break keyword is used to terminate the loop, even the condition is true. The control of the program passes to the outer statement after the body of the break statement.
a=0 while(a<5): if(a==3): break a = a+1 print(a) print("end of program")
Output:
1 2 end of program
continue
The continue keyword is used to stop the current iteration, and continues with the next statement
i = 0 while i <5: i += 1 if i == 3: continue print(i)
Output:
1 2 4 5
with
The with keyword is used in exception handling.
It makes code cleaner and much more readable. It simplifies the management of shared resources like file streams. For example:
#without using with statement file = open('file_path', 'w') file.write('hello world !') file.close()
An exception during the file.write() call in the above implementation can prevent the file from closing properly, which may lead to several bugs in the code.
Any changes in files do not reflect until the file is properly closed.
# using with statement with open('file_path', 'w') as file: file.write('hello world !')
In the above code, there is no need to call file.close()while using withstatement.
Thus, with statement helps to avoid bugs and ensures that a resource is appropriately released.
The with statement is popularly used with file streams, as shown above, and with Locks, sockets, sub-processes, etc.
lambda
The keyword lambda is used to define an anonymous function (function with no name). It is an inline function. A standard function is defined by using def keyword.
Lambda function can have multiple arguments but only one expression. In the following example, lambda function evaluates square of 1 to 5.
x=lambda x: x**2 for i in range(1,6): print(x(i))
Output:
1 4 8 16 20
global
When we declare a variable outside the function, it becomes global by default. If we want to access a global variable inside the function, we must use the global keyword.
a=10 def sum(): global a print(a**2) return a print(sum())
Output:
100 10
nonlocal
The keyword nonlocal is related to the global keyword. It is used to work with variables inside a nested function (function inside a function).
If we want to modify the value of a non-local variable inside a nested function, then we must declare it with nonlocal.
def outside_function(): a = 20 def inside_function(): nonlocal a a = 30 print("Inner function: ",a) inside_function() print("Outer function: ",a) outside_function()
Outside:
Inner function: 30
Outer function: 30
is
The is keyword is used to test if two-variable refers to the same object or testing object identity. It returns true if they refer to thesame object and return false if they do not refer to the same object, even if the two objects are 100% the equal. For example:
x=6 y=6 print(x is y)
Output:
True
In above code x and y refers to the same object.But in another example:
[] == [] True >>>[] is [] False >>> {} == {} True >>> {} is {} False
An empty list or dictionary is the same as another empty one. But they are not identical objects as they are stored separately in memory. It is because the list and dictionary are mutable which means value can be changed.
None
The None keyword is a special constant used to define a null value. It is an object of its own data type, the NoneType.
We must take special care that None does not indicate False, 0 or any empty list, dictionary, string, etc.
def return_void(): a = 1 b = 2 c = a * b
x = return_void() print(x)
Output:
None
In the above program, return_void()function does not return a value although it performs multiplication of two number. It prints None because function has returned None automatically.
yield
The yield statement prevents the function's execution temporally and returnsvalues to the caller.
It can produce a sequence of values whereas return sends a specified value back to its caller.
def simpleGenerator(): yield 1 yield 2 yield 3 # Driver code to check above generator function forvalue in simpleGenerator(): print(value)
Output:
1 2 3