In Python, keywords are designated words that serve particular functions and carry specific meanings, and they are exclusively reserved for their intended purposes. These keywords are permanently accessible in Python, indicating that there is no need to import them into your code.
List of Python Keywords
Below is the compilation of 35 keywords that are accessible 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 employed for the purposes of decision-making and creating loops.
Conditional Statements - if, elif, else
These keywords facilitate the execution of various code segments depending on specified 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.
Example
# 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 preceding example, we initialized a variable and employed conditional statement keywords such as if, elif, and else to evaluate the specified condition and execute the corresponding code based on the outcome.
Looping Construct - for, while
These keywords serve the purpose of executing code multiple times.
| 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 preceding example, we have created a list and utilized looping constructs such as for and while to traverse through it.
Loop Control - break, continue, pass
The keywords categorized under this classification are employed to alter the execution flow within 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 example provided above, a 'for' loop has been established to display numbers from 0 to 20. Within this loop, we have employed loop control statements to manipulate the execution flow inside the loop. Specifically, the break statement is utilized to halt the entire loop when the value of i reaches 14. The continue statement is implemented to bypass the loop iteration for even numbers. Additionally, the pass statement serves as a temporary placeholder where future code can be inserted.
Function and Class Definition Keywords
The terms categorized here are utilized for the purpose of defining functions, creating classes, and specifying 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 examine an example to illustrate the usage of the def keyword in Python.
Example
# use of def keyword
# defining a function
def greeting():
print("Welcome to our tutorial!")
# calling the function
greeting()
Output:
Welcome to our tutorial!
Explanation:
In the example provided, a function has been established to output a straightforward message by utilizing the def keyword.
Example: Use of return and yield Keyword
For illustrative purposes, let's examine an example that showcases the usage of the return and yield keywords 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 preceding example, a function named addnumbers has been established, utilizing the return keyword to provide the total of the numbers supplied to it. Additionally, we have created another function called generatenumber, where the yield keyword is employed to produce a generator object that encapsulates the array of generated numbers.
Example: Use of lambda Keyword
Let us consider an illustration to showcase the use of 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 preceding illustration, the lambda keyword has been utilized to create an anonymous function that computes and returns the square of the number it receives as an argument.
Example: Use of class Keyword
Let’s consider an illustration to showcase the utilization of the class keyword in Python.
Example
# use of class keyword
# declaring a user-defined class using class keyword
class Employer:
name = "Example"
industry = "Education"
Explanation:
In this instance, we have utilized the class keyword to define a custom class by employing the keyword class.
Exception Handling Keywords
The keywords belonging to this category are utilized for managing 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 preceding illustration, we have established a function. Within this function, we employed keywords such as try, except, finally, raise, and assert to manage various errors and exceptions that may arise during the function's execution.
Variable Scope and Namespace Keywords
The terms included in this category pertain to the access and alteration of variables.
| 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
To illustrate the use of the global keyword in Python, let’s consider an example.
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:
Explanation:
In the preceding example, a variable has been initialized, and a function has been defined. Within this function, the global keyword has been utilized to specify that the initialized variable should be treated as a global variable, and we have modified its value accordingly.
Example: Use of nonlocal Keyword
Let us examine an example to illustrate the usage of 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 preceding illustration, we created a nested function. Within the outer function, a variable was initialized. In the inner function, we utilized the nonlocal keyword to alter the variable defined in the parent function.
Logical and Boolean Keywords
These terms are utilized in Boolean expressions and logical operations.
| 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 us examine an example to illustrate the logical operation keywords utilized 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 preceding example, we initialized a pair of variables and utilized the keywords and, or, and not to evaluate different conditions.
Example: Use of Boolean Expression Keywords
Let us examine an example to illustrate the Boolean expression keywords utilized 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 example provided, we have established a function designed to determine whether a number is even. Within this function, the True keyword is utilized to indicate that the specified variable is an even number, while False is returned if the number is odd.
Import and Module Keywords
The terms classified under this category pertain to the management of modules and the importation of 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 preceding illustration, the keywords import, from, and as have been utilized to manage the process of importing functions.
Inheritance and Comparison Keywords
The terms in this category pertain to class inheritance and the relationships between objects.
| 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. |
Let us see an example showing how to use these keywords.
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 preceding example, we initialized a pair of variables. Subsequently, we employed the keywords is and in to ascertain whether both variables point to the identical object and element within a specified list.
Asynchronous Programming Keywords
These keywords are utilized in the context of 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("Example")
await asyncio.sleep(1) # pausing for 1 second without blocking
print("Tech")
async def main():
await greeting() # waiting for greeting to finish
await main()
Output:
Example
Tech
Explanation:
In the preceding example, the asyncio module has been imported. Subsequently, the async keyword has been utilized to define functions that operate asynchronously. Additionally, the await keyword has been employed to temporarily halt the execution of these asynchronous functions.
Python Program to Print All Keywords
According to Python version 3.11, there exists a total of 35 keywords. In this section, we will illustrate how to display all the keywords used 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 preceding section, we utilized the kwlist property from the keyword module to retrieve the collection of keywords available in Python.
What are Soft Keywords in Python?
In addition, Python comprises four soft keywords that function as keywords only in specific situations. Unlike standard keywords, these particular keywords can still be employed as variable names or function identifiers.
For example, the terms match and case were added to facilitate structural pattern matching. Nevertheless, because these are considered soft keywords, they can also be utilized as variable identifiers in scenarios that do not involve pattern matching.
Conclusion
In Python, keywords are designated terms that hold specific meanings and are fundamental to the language's syntax and framework. These keywords facilitate essential programming concepts, including control flow, data manipulation, and the declaration of functions. A solid understanding of these keywords is crucial for crafting code that is both clean and easy to read.
Python Keywords - MCQs
- Identify the correct use of the assert keyword for validating the positive value of a variable x.
- assert x > 0, "Value is not positive"
- assert (x > 0): "Value is not positive"
- assert x < 0: "Value is not positive"
- assert(x > 0, "Value is not positive")
Response: a) assert x > 0, "Value is not positive"
- Determine the result of executing the provided code:
try:
x = 10 / 0
except ZeroDivisionError:
print("Can't divided by zero")
finally:
print("End")
- Can't divided by zero End
- Error
- Execute without printing anything
- Can't divided by zero
Response: a) Division by zero is not permissible
- Considering the subsequent code snippet:
x = 10
if x > 5:
pass
print("Code executed")
What is the role of the pass keyword in this code?
- To exit from the program
- Continue the Loop
- Nothing but act as a placeholder
- Skips to next line of code
- Which of the following statements given below demonstrate correctly about nonlocal keywords?
- Declares a global variable inside a function
- Updating a variable within the local scope
- Updating a variable in the nearest enclosing scope (excluding global)
- Import a variable from a module
- In which of the scenarios is the keyword most commonly used?
- Handles arithmetic operations
- Manages the file operations efficiently
- Declares functions and methods
- Loops through the sequence