Python keywords are reserved words used for specific purposes that have specific meanings and functions, and these keywords cannot be used for anything other than their specific use. These keywords are always available in Python, which means you don’t need to import them into the code.
List of Python Keywords
The following is the list of 35 keywords available in Python
| 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 us discuss these keywords with the help of examples.
Control Flow Keywords
These Python keywords are utilized for decision-making and looping.
Conditional Statements – if, elif, else
These keywords are used to execute different blocks on the basis of conditions.
| Keyword | Description |
|---|---|
| if | This keyword is used to execute a block if the condition is True. |
| elif | This keyword is used to specify additional conditions if the previous ones fail. |
| else | This keyword is used to execute a block if all previous conditions are False. |
Let us see an example showing how to use these keywords.
# use of if, elif, else keywords
# initializing a variable
a = 20
# checking if the variable is greater than, equal to, or less than 20
if a > 20:
print("Greater than 20")
elif a == 20:
print("Equal to 20")
else:
print("Less than 20")
Output:
Equal to 20
Explanation:
In the above example, we have initialized a variable and used the conditional statement keywords like if, elif, and else to check for the given condition and execute the code accordingly.
Looping Construct – for, while
These keywords are used to execute code repeatedly.
| Keyword | Description |
|---|---|
| for | This keyword is used to iterate over a sequence, such as list, tuple, dictionary, etc. |
| while | This keyword is used to repeat execution while a condition remains True. |
Let us see an example showing how to use these keywords.
Example
# use of for, while keywords
# defining a list
shopping_bag = ['apples', 'bread', 'eggs', 'milk', 'coffee beans', 'tomatoes']
print("Given List:", shopping_bag)
print("\nIterating Over List using 'for' Loop:")
# iterating over the list using for loop
for item in shopping_bag:
print(item)
print("\nIterating Over List using 'while' Loop:")
# iterating over the list using while loop
index = 0
while index < len(shopping_bag):
print(shopping_bag[index])
index += 1
Output:
Given List: ['apples', 'bread', 'eggs', 'milk', 'coffee beans', 'tomatoes']
Iterating Over List using 'for' Loop:
apples
bread
eggs
milk
coffee beans
tomatoes
Iterating Over List using 'while' Loop:
apples
bread
eggs
milk
coffee beans
tomatoes
Explanation:
In the above example, we have initialized a list and make use of the looping constructs like for and while to iterate over it.
Loop Control – break, continue, pass
The keywords under this classification are used to change the flow of execution inside a loop.
| Keyword | Description |
|---|---|
| break | This keyword immediately exits the loop. |
| continue | This keyword is used to skip the current iteration and moves to the next. |
| pass | This keyword acts as a placeholder (does nothing). |
Let us see an example showing how to use these keywords.
Example
# use of break, continue, pass keywords
for i in range(20):
if i == 14:
break # terminating the loop completely when i is 14
if i % 2 == 0:
continue # skipping the rest of the loop for even numbers
if i == 9:
pass # does nothing
print(i)
Output:
1
3
5
7
9
11
13
Explanation:
In the above example, we have created a ‘for’ loop to print the numbers ranging from 0 to 20. Inside this loop, we have used the loop control keywords to change the flow of execution inside the loop. For instance, we have used the break keyword to terminate the entire loop when i becomes 14. The continue keyword is used to skips the loop for even numbers. We have used the pass keyword as a placeholder where the code can be added later.
Function and Class Definition Keywords
The keywords under this category are used to define functions, classes, and return values.
| Keyword | Description |
|---|---|
| def | This keyword is used to define a function. |
| return | This keyword is used to return a value from a function. |
| yield | This keyword returns a generator object. |
| lambda | This keyword is used to define anonymous function. |
| class | This keyword allows us to define a class. |
Let us see some examples showing how to use these keywords.
Example: Use of def Keyword
Let’s consider an example to demonstrate the def keyword in Python.
Example
# use of def keyword
# defining a function
def greeting():
print("Welcome to Learn Python App!")
# calling the function
greeting()
Output:
Welcome to Learn Python App!
Explanation:
In the above example, we have defined a function to print a simple statement using the def keyword.
Example: Use of return and yield Keyword
Let’s take an example to demonstrate the return and yield keyword in Python.
Example
# use of return, yield keywords
# defining a function to add numbers
def add_numbers(num1, num2):
# using return keyword
return num1 + num2
# defining a function to generate number
def generate_number(num1):
for i in range(num1):
# using yield keyword
yield i
# printing results
print("Addition of 12 and 5 is", add_numbers(12, 5))
for i in generate_number(5):
print("Generated Number:", i)
Output:
Addition of 12 and 5 is 17
Generated Number: 0
Generated Number: 1
Generated Number: 2
Generated Number: 3
Generated Number: 4
Explanation:
In the above example, we have defined a function as add_numbers(), where we have used the return keyword to return the sum of the numbers passed to it. We have then defined another function as generate_number(), where we have used the yield keyword to return the generator object containing the list of numbers generated.
Example: Use of lambda Keyword
Let us take an example to demonstrate the lambda keyword in Python.
Example
# use of lambda keyword
# anonymous function using lambda
square_of_num = lambda num: num * num
# printing the result
print("Square of 12 is", square_of_num(12))
Output:
Square of 12 is 144
Explanation:
In the above example, we have used the lambda keyword to define anonymous function to return the square of the number passed to it.
Example: Use of class Keyword
Let’s take an example to demonstrate the class keyword in Python.
Example
# use of class keyword
# declaring a user-defined class using class keyword
class Employer:
name = "Learn Python App"
industry = "Education"
Explanation:
In this example, we have used the class keyword to declare a user-defined class using the keyword called class.
Exception Handling Keywords
The keywords under this category are used to handle errors and exceptions.
| Keyword | Description |
|---|---|
| try | This keyword is used to define a block to catch errors |
| except | This keyword is used to handle exceptions |
| finally | This keyword helps execute after try-except |
| raise | This keyword is used to raise an exception manually |
| assert | This keyword is used to define debugging statement |
Let us see an example showing how to use these keywords.
Example
# use of try, except, finally, raise, assert keyword
def func_one(x):
try:
assert x > 0, "x must be a positive number" # AssertionError if x <= 0
result = 10 / x # Might raise ZeroDivisionError
except ZeroDivisionError:
print("Error: Division by zero")
result = float('inf') # handling error
raise # re-raising the error
except AssertionError as e:
print(f"Assertion Error: {e}")
result = None
finally:
print("This will always execute")
return result
# printing results
print("For x = 6:", func_one(6), "\n")
print("For x = 0:", func_one(0), "\n")
print("For x = -6:", func_one(-6), "\n")
Output:
This will always execute
For x = 6: 1.6666666666666667
Assertion Error: x must be a positive number
This will always execute
For x = 0: None
Assertion Error: x must be a positive number
This will always execute
For x = -6: None
Explanation:
In the above example, we have defined a function. Inside this function, we have used the keywords like try, except, finally, raise, and assert to handle the different errors and exceptions that might raise during the execution of the function.
Variable Scope and Namespace Keywords
The keywords under this category are used for variable access and modification.
| Keyword | Description |
|---|---|
| global | This keyword is used to declare a global variable |
| nonlocal | This keyword is used to modify parent function variables |
Let us see some examples showing how to use these keywords.
Example: Use of global Keyword
Let’s take an example to demonstrate the global keyword in Python.
Example
# use of global keyword
# initializing p as 12
p = 12
# defining a function
def func_one():
# using global keyword to declare p as global variable
global p
# updating the value of p to 19
p = 19
# printing results
func_one()
print(p)
Output:
19
Explanation:
In the above example, we have initialized a variable and defined a function. Inside this function, we have used the global keyword to declare the initialized variable as global and updated its value.
Example: Use of nonlocal Keyword
Let’s consider an example to demonstrate the nonlocal keyword in Python.
Example
# use of nonlocal keyword
# defining an outer function
def func_outer():
# initializing p as 13
p = 13
# defining an inner function
def func_inner():
nonlocal p # accessing the 'p' from the outer function
# updating the value of p to 25
p = 25
print("Inner function:", p)
# calling the inner function
func_inner()
print("Outer function:", p)
# calling the outer function
func_outer()
Output:
Inner function: 25
Outer function: 25
Explanation:
In the above example, we defined a nested function. Inside the outer function, we have initialized a variable. Inside the inner function, we have used the nonlocal keyword to modify the variable of the parent function.
Logical and Boolean Keywords
These keywords are used in logical operations and Boolean expressions.
| Keyword | Description |
|---|---|
| and | This keyword represents Logical AND |
| or | This keyword represents Logical OR |
| not | This keyword represents Logical NOT |
| True | This keyword represents Boolean True value |
| False | This keyword represents Boolean False value |
Let us see an example showing how to use these keywords.
Example: Use of Logical Operation Keywords
Let’s consider an example to demonstrate the logical operation keywords in python.
Example
# use of and, or, not keywords
x = 12
y = 19
# Using 'and'
if x > 0 and y > 0:
print("Both x and y are positive")
# Using 'or'
if x > 15 or y > 15:
print("At least one of x or y is greater than 10")
# Using 'not'
if not x == 0:
print("x is not equal to 0")
Output:
Both x and y are positive
At least one of x or y is greater than 10
x is not equal to 0
Explanation:
In the above example, we have initialized two variables and used the and, or, and not keywords to check various conditions.
Example: Use of Boolean Expression Keywords
Let’s consider an example to demonstrate the Boolean expression keywords in Python.
Example
# use of True, False keywords
# defining a function to check even number
def chck_even(number):
"""Checks if a number is even."""
if number % 2 == 0:
return True
else:
return False
print(f"Is 24 even? {chck_even(24)}")
print(f"Is 57 even? {chck_even(57)}")
Output:
Is 24 even? True
Is 57 even? False
Explanation:
In the above example, we have defined function to check for even number. Inside this function, we have used the True keyword to return that given variable is an even number and False in case of odd number.
Import and Module Keywords
The keywords under this category are used for module handling and importing functions.
| Keyword | Description |
|---|---|
| import | This keyword is used to import a module |
| from | This keyword allows us to import specific part of a module |
| as | This keyword is used to rename imported module |
Let us see an example showing how to use these keywords.
Example
# use of import, from, as keywords
import math as m
from math import pi
Explanation:
In the above example, we have used the import, from, and as keywords to handle the importing functions.
Inheritance and Comparison Keywords
The keywords under this category are used for class inheritance and object relationships.
| Keyword | Description |
|---|---|
| is | This keyword is used to check if two objects are the same |
| in | This keyword is used to check membership in lists, tuples, etc. |
Example
# use of is, in keywords
p = 14
q = 14
# 'is' checks if both variables refer to the same object in memory
if p is q:
print("p and q refer to the same object")
# 'in' checks for membership in a sequence (string, list, tuple, etc.)
lst_1 = [13, 25, 46, 14, 59]
if p in lst_1:
print("p is present in lst_1")
Output:
p and q refer to the same object
p is present in lst_1
Explanation:
In the above example, we have initialized two variables. We have then used the is and in keywords to check if both variables refer to the same object and member of a given list.
Asynchronous Programming Keywords
These keywords are used for asynchronous programming.
| Keyword | Description |
|---|---|
| async | This keyword is used to define an asynchronous function. |
| await | This keyword allows us to pause async function execution |
Let us see an example showing how to use these keywords.
Example
# use of async, await keywords
# importing the required module
import asyncio
async def greeting():
print("Learn Python
")
await asyncio.sleep(1) # pausing for 1 second without blocking
print("App")
async def main():
await greeting() # waiting for greeting to finish
await main()
Output:
Learn Python
App
Explanation:
In the above example, we have imported the asyncio module. We have then used the async keyword while defining asynchronous functions. We have also used the await keyword to pause the execution of async functions.
Python Program to Print All Keywords
As per Python 3.11, there are 35 keywords. Here, we are going to take an example to print all keywords in Python.
Example
# importing the keyword module
import keyword
# using kwlist to display list of keywords
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']
Explanation:
In the above, we have used the kwlist attribute from the keyword module to get the list of keywords in Python.
What are Soft Keywords in Python?
Python also includes four soft keywords, which act like keywords only under certain conditions. Unlike regular keywords, these keywords can still be utilized in the form of variable names or function identifiers.
For instance, the keywords like match and case were introduced for the purpose of structural pattern matching. However, since they are soft keywords, we can used them as variable names in non-pattern-matching contexts.
Conclusion
Python keywords are reserved words having special meanings and are central to the syntax and structure of a language. They provide important programming concepts such as control flow, manipulation of data, and function declaration. Good knowledge of these keywords are important in writing clean, and readable code.
Leave a Reply