In a Programming language, the keyword is a word reserved by a program because the word has a special meaning. Each programming language has a set of its own keywords. The keywords should not be used as variables since its reserved from use. Keywords are also called as Reserved words. Here is the list of Python keywords:
False | await | else | import | pass |
None | break | except | in | raise |
True | class | finally | is | return |
and | continue | for | lambda | try |
as | def | from | nonlocal | while |
assert | del | global | not | with |
async | elif | if | or | yield |
Let’s have a look at each one of these Python keywords:
Table of Contents
False:
The Python keyword ‘False’ a Boolean value and result of a comparison operation. When a given condition is false, it returns False. A zero value is considered as False.
True:
The True keyword is also Boolean value and result of a comparison operation. When a given condition is true, it returns True. All non-zero values are considered as True.
>>> print(2>3) False >>> print(2<3) True
async:
An asynchronous function in Python is typically called a ‘coroutine’, which is just a function that uses the async keyword. Calling the asynchronous function doesn’t execute them, a coroutine object is returned instead, which can then be passed to the event loop to be executed later on. The async keyword is a part of aysncio library.
await:
The await keyword is also a part of aysncio library. await can be used only inside the async functions. It suspends the execution of coroutine until the awaitable it takes completes and returns the result.
import asyncio import datetime async def func(): print(datetime.datetime.now()) await asyncio.sleep(10) print(datetime.datetime.now()) loop = asyncio.get_event_loop() loop.run_until_complete(func())
2020-07-06 14:27:36.237069 2020-07-06 14:27:46.237487
import:
The Python keyword ‘import’ imports other modules to the current Python script. The imported module itself contains a runnable Python code.
>>> import math >>> print(math.sqrt(16)) 4.0
as:
We can create an alias name for a module while importing it using ‘as’ keyword. We can refer to the imported module in our code using the alias name. If we are creating an alias name for a module, then we have to use the alias name only, else we will get an error.
import math as module print(module.sqrt(16)) print(math.sqrt(16))
4.0 Traceback (most recent call last): File "sample.py", line 4, in <module> print(math.sqrt(16)) NameError: name 'math' is not defined
from:
While the import keyword, imports a module, the from keyword imports the specific function or attribute from a module into our code.
from math import sqrt print(sqrt(16))
Importing math module, imports whole math module into the namespace. By using from keyword we can import only the specific function which avoids dumping our namespace with unwanted function or attributes.
To import more than one function from the same module, we can use comma.
from math import sqrt, factorial
None:
The Python keyword None defines null value, void, or no value at all. It is not the same as 0 or False. The datatype of None is ‘NoneType’.
def func(): pass print(func()) print(type(func())) print(None==False) print(None==None)
None <class 'NoneType'> False True
Here the function func(), is not returning anything, hence the return value is None.
if:
The Python keywords ‘If and Else’ are the decision making control statements which decides the direction of flow of program execution. The block of code that follows the ‘if’ statement at the same indent level will be executed if the condition given in the ‘if’ statement is true.
if 2<3: print("The condition is True")
The condition is True
else:
Suppose you want to execute the negative condition of ‘if’ condition, then ‘else’ statement is used. If the given condition in ‘if’ statement returns False, then else block gets executed.
if 2>3: print("The condition is True") else: print("The condition is False")
The condition is False
elif:
elif keyword is to check more than one condition. It’s a short form of else-if. Like ‘if’ statement, if the condition given in the ‘elif’ statement is True, then the block of code under the ‘elif’ statement gets executed.
if 2>3: print("The condition is True") elif 2==2: print('Both are equal') else: print("The condition is False")
Both are equal
pass:
The pass statement does nothing. To declare an empty class, function, if, elif or else statement with no content, we can use the pass statement.
class Sample: pass def func(): pass if 2>3: pass elif 2==2: pass else: pass
break:
The break keyword breaks the execution of the loop and transfers control to the end of the loop. It is used along with for and while loops.
i=1 while(i<=10): print(i) if i==5: break i+=1
1 2 3 4 5
The above code prints number from 1 to 10. With the break statement, we are breaking the loop when the variable ‘i’ becomes 5. Even though we have given a break statement inside ‘if’, it’s not applicable to if. It’s applicable to the for/while surrounding the ‘if’ statement.
Continue:
With the “continue” statement we can stop the current iteration alone and continue with the next iterations. Like break statement, we use continue with for/while loops.
i=0 while(i<=5): i+=1 if i==3: continue print(i)
1 2 4 5 6
in:
It checks for the existence of a value in a sequence(lists, strings, tuple,etc.). And it’s also used to iterate through a sequence in for loop.
l=[1,2,3,4] print(1 in l) print(5 in l) for i in l: print(i)
True False 1 2 3 4
is:
The Python keyword ‘is’ checks if two objects are the same. The ‘==’ operator checks if both variables are the same, where ‘is’ check if both the variables refer to the same object.
a=[1,2,3] b=a.copy() print(a==b) print(a is b)
True False
The list b is a copy of elements present in the list a. The elements in both the lists are the same hence the ‘==’ returns True. The lists b and a don’t refer to the same object hence the ‘is’ operator returns False.
class:
The Python keyword ‘class’ creates a new class in Python. A class is a collection of attributes and behavior that represents a real-life entity. The class is a blueprint to create objects.
class Employee: name='xyz' age=27 def calculate_salary(self): pass def get_designation(self): pass
def:
The Python keyword ‘def ‘ creates a function in Python. A function is a block of code, which gets executed when the function is called. Organizing the code into function makes the code more readable and reduces the redundant code.
def sample_function(): print("A sample function")
A sample function
return:
The return keyword is used inside a function. When a return statement is encountered, the function will be exited. We can also use the return keyword to return something from the function.
def func(a,b): total=a+b return total print("Total is: "+str(total)) total=func(5,10)
The print statement inside the function will not be executed because the function exits when it encounters a return statement.
lambda:
The Python keyword ‘lambda’ creates a one-line function in Python, which has no name and does not return anything. It can take any number of arguments but has only one expression.
output=lambda a,b,c:a*b*c print(output(5,10,15))
750
try, except:
In Python, we handle the exception using try and except block. The code written inside the try block will get executed whenever the program is run. The code inside the except block will get executed if there is an exception caused by the code inside the try block. That means the code inside the except block is a response to the exception caused by the code inside the try block.
Syntax errors are not an exception. In case of exception, the program stops abruptly due to unhandled exceptions caused by the syntactically correct code. You can add an except block, to handle the exception and the program continues after that.
def get_reminder(num1,num2): try: result=num1%num2 return result except: print('Exception Occured') return print(get_reminder(10,3)) print(get_reminder(10,0))
1 Exception Occured None
raise:
As a programmer, you can choose to throw an exception based on conditions. Use ‘raise’ keyword to throw an exception, if a certain condition occurs.
x=5 while(x>=0): print(x) x-=1 else: raise Exception('Negative numbers are not allowed')
5 4 3 2 1 0 Traceback (most recent call last): File "sample.py", line 6, in <module> raise Exception('Negative numbers are not allowed') Exception: Negative numbers are not allowed
finally:
The Python keyword ‘finally’ is used along with the try-except block. The finally block does some clean-up after the code execution. The code inside finally block gets executed no matter what. It’s doesn’t matter whether there is an exception inside try or there is no exception at all.
def get_reminder(num1,num2): result=None try: result=num1%num2 except: print('Exception Occured') finally: print('Cleaning Up!') return result if result is not None else None print(get_reminder(10,3)) print(get_reminder(10,0))
Cleaning Up! 1 Exception Occured Cleaning Up! None
assert:
The Python keyword ‘assert’ is used for debugging. Prior to running the module, using the assert statement, a programmer can declare the condition to be true while writing the code. If the condition is True, the next line of code will get executed, else the program throws an AssertionError exception.
x=5 assert x==5 assert x==7
Traceback (most recent call last): File "sample.py", line 4, in <module> assert x==7 AssertionError
We can also provide an error message, along with the assert statement, condition followed by a comma, and the error message.
x=5 assert x==5 assert x==7, "Numbers are not equal"
Traceback (most recent call last): File "sample.py", line 4, in <module> assert x==7, "Numbers are not equal" AssertionError: Numbers are not equal
and:
The ‘and’ keyword is a logical operator. We can use ‘and’ operator to check for multiple conditions. Returns True only if both the conditions are True. The truth table for ‘and’ operator is:
A | B | A and B |
---|---|---|
True | True | True |
True | False | False |
False | True | False |
False | False | False |
or:
The ‘or’ keyword is a logical operator. We can use ‘or’ operator to check for multiple conditions. Returns True if any of the one condition is True. The truth table for ‘or’ operator is:
A | B | A or B |
---|---|---|
True | True | True |
True | False | True |
False | True | True |
False | False | False |
not:
The ‘not’ keyword is a logical operator. It inverts the truth value. The truth table for ‘not’ operator is:
A | not A |
---|---|
True | False |
False | True |
for:
Python keyword ‘For’ is a looping statement. The for loop is used to iterate over a sequence like strings, lists, tuples, etc. The for loop is used to execute a set of statements for each item in a sequence.
l=[1,2,3] for i in l: print(i**2)
1 4 9
while:
Like ‘for’ loop, the while loop is also used to iterate over a sequence. With a while loop, we execute the block of code as long as the condition given the while statement is True.
The below code prints the first three elements of a list.
l=[5,7,6,4,10] i=0 while(i<3): print(l[i]) i+=1
5 7 6
del:
The del keyword deletes reference to an object. Using del keyword e can also delete a specific item from a list or dictionary.
l=[5,7,6,4,10] d={'a':1,'b':2,'c':3}
>>> del l[2] >>> l [5, 7, 4, 10] >>> del l >>> l Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'l' is not defined >>> del d['b'] >>> d {'a': 1, 'c': 3} >>> del d >>> d Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'd' is not defined
with:
In Python, context managers provide an easy way to manage resources. When creating a new context manager class, make sure that it contains these methods: __enter__() and __exit__(). The __enter__() method returns the list of resources to be managed and __exit__() does the cleanup operation. The sequence of code execution will be:
- __enter__()
- code within with block
- __exit__()
with open('output.txt' , 'w') as file: file.write('Hello World')
The above code opens the file in write mode and writes into it. The file objects have their own __enter__() and __exit__() methods hence they act as their own context manager.
In this example, the exit method closes all the opened files. The with statement ensures that the __exit__() method is called at the end. Even if the program results in an error, the __exit__() method will be called.
yield:
The usage of yield keyword is similar to the return keyword inside a function. But unlike return, yield does not destroy the state of local variables of a function and when the function is called again, execution resumes from the last yield point.
The use of yield function makes a function as a generator.
def power_of_two(num): for i in num(i): yield 2**i result=power_of_two(5) print(result)
<generator object power_of_two at 0x028B2E40>
The generator generates one value at a time. Use next() to print the next item in a generator.
>>> next(result) 1 >>> next(result) 2 >>> next(result) 4 >>> next(result) 8 >>> next(result) 16
We can also use for loop to print each item in a generator.
>>> for i in result: ... print(i) ... 1 2 4 8 16
global:
Even though we define the variable with the same name inside and outside the function, by changing the value of the variable in the local scope doesn’t affect the value of the variable in the global scope. What if you want to change the value of the global variable inside the function.
Inside the function, we have to use the keyword ‘global’ before a variable so that we can change the variable at the global level.
var=5 def func(): global var print(var) var=10 func() print(var)
5 10
nonlocal:
The usage of nonlocal keyword is similar to the global keyword. But the nonlocal keyword is used in nested functions. The variable is declared in the outer function. By using the nonlocal keyword, we can change the variable of the outer function inside the inner function.
def outer_func(): var='Outer function variable' def inner_func(): nonlocal var print(var) var="Changed in inner function" inner_func() print(var) outer_func()
Outer function variable Changed in inner function
We have covered the basic introduction of all Python keywords. We will be learning more in the upcoming tutorials.