Python – Keywords
In this tutorial you will learn python in detail.
There are a set of reserved keywords in Python that cannot be used as variable names, function names or any other identifiers. Python keywords have specific meaning and purpose. These keywords are the fundamental building blocks of any Python program. You can’t assign something to these keywords. You will get SyntaxError if you try to assign.
This article will help you on:
- Identify Python keywords
- Understand what each keyword is used for
- Work with keywords programmatically using the keyword module
There are 35 keywords in Python. Here they are:
Use help() command to get a list of available keywords
$ help (“keywords”)
To know more information about a specific keyword, you can use help() by passing that keyword. For example,
$ help(“pass”)
Python Keywords and Their Usage
Value Keywords: True, False, None
In Python True and False keywords are written in uppercase, but in contrast they are written in lowercase. The True keyword is used as Boolean true value and False is used as Boolean false value. The True keyword is the same as 1 (False is the same as 0)
Example code:
#Keywords True, False
print (5 < 10) #it is true
print (15 < 10) #it is false
Output:
True
False
The None keyword
This keyword represents no value or absence of value. None is a special constant.
Example code:
#Keyword None
deftest_function(): #This function will return None
print(‘Hello’)
x = test_function()
print(x)
Output:
Hello
None
Operator Keywords: and, or, not, in, is
The and Keyword
Few Python keywords are used as operators. Keyword and is a logical operator. To combine conditional statements, we use logical operators. If both the expressions are true, then the result will be true else it returns false.
<expr1> and <expr2>
For example:
if 6 > 4 and 10 < 15:
print (“Both statements are True”)
else:
print (“At least one of the statements are False”)
Output:
Both the statements are True
The or Keyword
The or keyword is used to determine if at least one of the operands is true. It returns true if any one of the operands is true.
<expr1> or <expr2>
Example code:
if 5 > 3 or 5 > 10:
print("At least one of the statements are True")
else:
print("None of the statements are True")
Output:
At least one of the statements are True
The not Keyword
Python’s not keyword is a logical operator. It returns true if the statements are not true, otherwise it will return false.
Example:
x = False
print (not x)
Output:
True
The in Keyword
This keyword is a membership operator. The in Keyword is used to check whether the element is present in a list or not.
Example code:
fruits = ["apple", "banana", "cherry"]
if "banana" in fruits:
print("yes")
Output:
yes
And also, it is used to iterate through a sequence in a for loop:
Example code:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
Output:
apple
banana
cherry
The is Keyword
This keyword is used to check if two variables refer to the same object. It returns True if the two objects are the same object. It returns False if they are not the same object, even if the two objects are 100% equal.
Example code:
x = ["apple", "banana", "cherry"]
y = x
print (x is y)
Output:
True
Control Flow Keywords: if, elif, else
These control flow keywords allow you to use conditional logic and execute code with certain conditions.
The if keyword
This keyword is used to write conditional statements, and allow you to execute a block of code only if a condition is True.
Example code:
x = 5
if x > 6:
print("YES")
else:
print("NO")
Output:
NO
The elif keyword
The elif in short else if, used in conditional statements. The elif Keyword is only valid after an if statement. And you can use as many elif statements as per need.
Example code:
for i in range(-5, 5):
if i > 0:
print("YES")
elif i == 0:
print("WHATEVER")
else:
print("NO")
Output:
NO
NO
NO
NO
NO
WHATEVER
YES
YES
YES
YES
The else Keyword
This keyword is also used in conditional statements and decides what to do if the condition is False.
Example code:
x = 2
if x > 3:
print("YES")
else:
print("NO")
Output:
NO
Iteration Keywords: for, while, break, continue
A very important programming concept is Looping and Iteration. Understanding these loops and iterations will improve as a programmer.
The for keyword
The for keyword is used to iterate through a sequence like list, tuple etc.
Example code:
fruits = ["strawberry", "mango", "orange"]
for x in fruits:
print(x)
Output:
strawberry
mango
orange
The while Keyword
This keyword is used to create while loop. The while loop continues until the statement is false.
Example code:
x = 0
while x < 9:
print(x)
x = x + 1
Output:
0
1
2
3
4
5
6
7
8
The break keyword
In order to break out of a loop you can use break keyword. This works for both for and while loops.
Example:
i = 1
while i < 9:
print(i)
if i == 3:
break
i += 1
Output:
1
2
3
The continue Keyword
When you want to skip to the next loop iteration, Python provides continue keyword. It allows you to stop execution of current loop iteration and moves on to the next iteration.
Example code:
for i in range(9):
if i == 3:
continue
print(i)
Output:
0
1
2
4
5
6
7
8
Structure Keywords: def, class, with, as, pass, lambda
The def keyword
This keyword is used to create a function.
Example code:
def my_function():
print("Hello from a function")
my_function()
Output:
Hello from a function
The class keyword
You use the class keyword to define a class in Python. A Class is like an object constructor for creating objects.
Example code:
class Person:
name = "John"
age = 36
p1 = Person()
print(p1.name)
Output:
John
The with Keyword
The with keyword is used in exception handling to make code cleaner and readable.
Example code:
with open("names.txt") as input_file:
for name in input_file:
print(name.strip())
Output:
David
Jhon
Ham
Lues
The as keyword
The as keyword is used to create an alias.
Example code:
import calendar as c
print(c.month_name[1])
Output:
January
The pass Keyword
There are no block indicators to specify the end of a block. The pass keyword is used to specify that block is intentionally kept blank. This keyword is used as a placeholder for future code.
def myfunction:
pass
#This kind of empty function definition, would raise an error without the pass statement.
The lambda Keyword
In Python to define a function doesn’t have any name lambda keyword is used. This function have only one expression and can take any number of arguments. The results are returned.
Example code:
x = lambda a, b, c : a + b + c
print(x(5, 6, 3))
Output:
14
Returning Keywords: return, yield
The return keyword
This is used to exit a function and return a value.
Example code:
def myfunction():
return 3+3
print(myfunction())
Output:
6
The yield keyword
A function which uses a yield statement, returns a generator. The generator is passed to Python’s built-in next() to get the next value that is returned form the function.
Example code:
>>> def family():
... yield "Pam"
... yield "Jim"
... yield "Cece"
... yield "Philip"
...
>>> names = family()
>>> names
<generator object family at 0x7f47a43577d8>
>>> next(names)
'Pam'
>>> next(names)
'Jim'
>>> next(names)
'Cece'
>>> next(names)
'Philip'
>>> next(names)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
Import Keywords: import, from
The import keyword
This keyword is used to import a module to use in your Python program.
Example code:
$ import collections
$ collections.Counter()
Counter()
The from Keyword
This keyword is used along with import keyword to import something specific from a module.
Example code:
from datetime import time
x = time(hour=15)
print(x)
Exception-Handling Keywords: try, except, raise, finally, assert
The try keyword
Every exception handling block begins with try keyword.
# (x > 3) will raise an error because x is not defined:
try:
x > 3
except:
print("Something went wrong")
print("Even if it raised an error, the program keeps running")
Output:
Something went wrong
Even if it raised an error, the program keeps running
The except keyword
This keyword is used along with try keyword to define what to do when exceptions are raised.
You can use any number of except blocks with a single try.
Example code:
# (x > 3) will raise an error because x is a string and 3 is a number, and cannot be compared using a '>':
x = "hello"
try:
x > 3
except NameError:
print("You have a variable that is not defined.")
except TypeError:
print("You are comparing values of different type")
Output:
You are comparing values of different type
The raise keyword
In Python when you want to raise an exception, you can use raise keyword. You can define the type of error to be raised and the text to print.
Example code:
x = "hello"
if not type(x) is int:
raise TypeError("Only integers are allowed")
Output:
Traceback (most recent call last):
File "demo_ref_keyword_raise2.py", line 4, in <module>
raise TypeError("Only integers are allowed")
TypeError: Only integers are allowed
The finally keyword
This keyword is used in specific code to execute no matter what happens in the try, except blocks.
Example code:
try:
x > 3
except:
print("Something went wrong")
else:
print("Nothing went wrong")
finally:
print("The try...except block is finished")
Output:
Something went wrong
The try...except block is finished
The assert Keyword
When debugging a code, you can use assert keyword. For smooth flow of code assertions ae used.
This keyword lets programmer to know if a condition returns true, if not the failure of code doesn’t allow the code to execute. It raises an AssertionError along with the optional message provided.
Example code:
a = 4
b = 0
# using assert to check for 0
print ("The value of a / b is : ")
assert b != 0, "Divide by 0 error"
print (a / b)
Output:
The value of a/b is :
Traceback (most recent call last):
File "/home/40545678b342ce3b70beb1224bed345f.py", line 10, in
assert b != 0, "Divide by 0 error"
AssertionError: Divide by 0 error
Asynchronous Programming Keywords: async, await
The async Keyword
To define an asynchronous function, the async keyword is used along with def.
Syntax:
async def <function>(<params>):
<statements>
The await keyword
In asynchronous functions to specify a point in the function, you can use await keyword.
Syntax:
await <some async function call>
# OR
<var> = await <some async function call>
Variable Handling Keywords: del, global, nonlocal
The del Keyword
In Python del keyword is used to delete variables, lists, or parts of a list etc.
Example code:
x = "hello"
del x
print(x)
Output:
Traceback (most recent call last):
File "demo_ref_keyword_del2.py", line 5, in <modulegt;
print(x)
NameError: name 'x' is not defined
The global keyword
If a variable is defined in a global scope and you want to modify that variable, you will need to use global keyword. This can be done by specifying global keyword before the variable you need to pull into the function.
Example code:
>> x = 0
>> def inc():
... global x
... x += 1
...
>>> inc()
>>> x
1
>>> inc()
>>> x
2
The nonlocal keyword
For the modifying variables inside nested functions, this nonlocal keyword is used. The nonlocal keyword declares that the variable is not local.
Example code:
def myfunc1():
x = "John"
def myfunc2():
nonlocal x
x = "hello"
myfunc2()
return x
print(myfunc1())
Output:
hello
The fundamental building blocks of Python program is the keywords. To improve your skills in Python, it is very important to understand the proper use of these keywords.