Python has a set of reserved keywords that have predefined meanings and cannot be used as variable names or identifiers. The following are the list of Python keywords:
and as assert async await break class continue def del elif else except False finally for from global if import in is lambda None nonlocal not or pass raise return True try while with yield
Note that async
and await
are introduced in Python 3.5 and are reserved keywords in Python 3.7 or later versions.
How to Identify Python Keywords:
In Python, you can identify the reserved keywords using the keyword
module. This module provides a function iskeyword()
which takes a string as an argument and returns True
if the string is a keyword and False
otherwise.
Here’s an example:
import keyword # List of strings to check words = ['if', 'else', 'elif', 'while', 'for', 'break', 'continue', 'assert', 'notakeyword'] # Iterate over the words and check if they are keywords for word in words: if keyword.iskeyword(word): print(word, 'is a keyword') else: print(word, 'is not a keyword')
Output:
if is a keyword else is a keyword elif is a keyword while is a keyword for is a keyword break is a keyword continue is a keyword assert is a keyword notakeyword is not a keyword
In the above example, the iskeyword()
function is used to check if each string in the words
list is a Python keyword. The output shows that the first eight words are keywords, while the last one is not.
Python Keywords and Their Usage:
Here’s a brief description of each Python keyword and its usage:
and
: A logical operator used for boolean expressions. It returnsTrue
if both operands areTrue
.
if x > 0 and y < 0: print('x is positive and y is negative')
2.as
: Used in import statements to create an alias for a module or its contents.
import numpy as np
3.assert
: A debugging aid that tests a condition and triggers an exception if the condition is not true.
assert x > 0, 'x must be positive'
4.async
and await
: Used for asynchronous programming in Python. async
defines a coroutine function and await
suspends the execution of a coroutine until it is completed.
async def fetch_data(): # fetch data here return data async def process_data(): data = await fetch_data() # process data here
5.break
: Used in loops (for or while) to break out of the loop before its normal end.
while True: x = get_input() if x == 'quit': break process_input(x)
6.class
: Used to define a new class in Python.
class Car: def __init__(self, make, model, year): self.make = make self.model = model self.year = year
7.continue
: Used in loops to skip the current iteration and move on to the next one.
for i in range(10): if i % 2 == 0: continue print(i)
8.def
: Used to define a function in Python.
def square(x): return x ** 2
9.del
: Used to delete an object or attribute in Python.
x = [1, 2, 3] del x[1]
10.elif
: A keyword used in if statements to test multiple conditions.
if x > 0: print('x is positive') elif x == 0: print('x is zero') else: print('x is negative')
11.else
: A keyword used in if statements to specify the code block to execute when the condition is false.
if x > 0: print('x is positive') else: print('x is not positive')
12.except
: Used in try-except blocks to handle exceptions.
try: x = int(input('Enter a number: ')) except ValueError: print('Invalid input')
13..False
: A Boolean keyword in Python representing the logical value of false.
x = False
14.finally
: A keyword used in try-except-finally blocks to specify the code block to execute regardless of whether an exception was raised or not.
try: # some code here except: # handle the exception finally: # always executed
15.for
: A keyword used to create a loop that iterates over a sequence of values.
for i in range(5): print(i)
16.from
: A keyword used in import statements to import specific functions or classes from a module.
from math import sin, cos
17.`global
Operator Keywords: and, or, not, in, is:
The following are the operator keywords in Python:
and
: A logical operator used for boolean expressions. It returnsTrue
if both operands areTrue
.
if x > 0 and y < 0: print('x is positive and y is negative')
2.or
: A logical operator used for boolean expressions. It returns True
if at least one of the operands is True
.
if x > 0 or y > 0: print('x or y is positive')
3.not
: A logical operator used for boolean expressions. It returns True
if the operand is False
, and vice versa.
if not x > 0: print('x is not positive')
4.in
: A keyword used to check if a value is present in a sequence or collection.
if x in [1, 2, 3]: print('x is in the list')
5.is
: A keyword used to check if two variables refer to the same object in memory.
if x is None: print('x is None')
The nonlocal Keyword:
The nonlocal
keyword is used in Python to indicate that a variable is not local to the current function, but it is in the enclosing function’s scope. This keyword is used to modify the value of a variable that is defined in the outer function’s scope, without affecting other variables with the same name in other scopes.
Here’s an example to illustrate the use of the nonlocal
keyword:
def outer_function(): x = 10 def inner_function(): nonlocal x x += 5 print("Inner function:", x) inner_function() print("Outer function:", x) outer_function()
In this example, the outer_function()
defines a variable x
and then calls an inner function inner_function()
. The inner function modifies the value of x
using the nonlocal
keyword. The print()
statements in the outer function and inner function show that the value of x
is modified in the inner function, and the outer function is aware of the new value.
Output:
Inner function: 15 Outer function: 15
Note that the nonlocal
keyword can only be used to modify variables in the outer function’s scope, not the global scope. If you need to modify a global variable from within a function, you should use the global
keyword instead.
Iteration Keywords: for, while, break, continue:
The following are the iteration keywords in Python:
for
: A keyword used for iterating over a sequence, such as a list, tuple, or string. It can also be used to iterate over the keys or values of a dictionary.
for i in range(10): print(i)
2.while
: A keyword used to create a loop that continues as long as the condition is true.
i = 0 while i < 10: print(i) i += 1
3.break
: A keyword used to exit a loop prematurely. It can be used to terminate a loop when a specific condition is met.
for i in range(10): if i == 5: break print(i)
4.continue
: A keyword used to skip the current iteration of a loop and move on to the next iteration. It can be used to skip over certain values in a sequence or to skip over iterations that meet a specific condition.
for i in range(10): if i == 5: continue print(i)
These iteration keywords are used frequently in Python programming and are essential for creating loops and iterating over data structures.
Exception Handling Keywords – try, except, raise, finally, and assert:
The following are the exception handling keywords in Python:
try
: A keyword used to define a block of code that may raise an exception. If an exception occurs in the try block, it is caught by the following except block.except
: A keyword used to define a block of code that is executed if an exception is raised in the try block. The except block specifies which exception is being caught and can handle the exception appropriately.raise
: A keyword used to raise an exception manually. It can be used to raise an exception in response to a specific condition that is not caught by the try-except block.finally
: A keyword used to define a block of code that is always executed after the try-except block, regardless of whether an exception was raised or not. The finally block is used to release resources or perform other cleanup operations.assert
: A keyword used to raise an AssertionError if the expression passed as an argument evaluates to False. It is used for debugging and testing to ensure that certain conditions are met.
Here’s an example to illustrate the use of these keywords:
try: x = int(input("Enter a number: ")) if x < 0: raise ValueError("Number cannot be negative") else: print("Square of the number:", x ** 2) except ValueError as ve: print(ve) finally: print("End of program")
In this example, the try block takes an input from the user and checks whether the number is negative or not. If it is negative, it raises a ValueError. If it is not negative, it prints the square of the number. The except block catches the ValueError and prints an error message. The finally block is executed regardless of whether an exception was raised or not, and it prints a message indicating the end of the program.
Output:
Enter a number: -5 Number cannot be negative End of program
Exception handling is an essential part of writing robust and reliable code, and these keywords are used frequently in Python programming.
The pass Keyword:
The pass
keyword in Python is used as a placeholder statement in situations where you want to do nothing or when you are defining a block of code that will be implemented later. It is a null operation, which means that it does nothing and serves as a placeholder to ensure that the code runs without errors.
Here are some examples of the use of the pass
keyword:
- When defining a function or class that does not have any code yet:
-
def my_function(): pass class MyClass: pass
- In a loop where you want to do nothing for a certain iteration:
for i in range(10): if i == 5: pass else: print(i)
In this example, the
pass
keyword is used in the if statement to indicate that nothing should happen when the value ofi
is equal to 5.- When defining an exception that you want to handle later:
-
class MyException(Exception): pass
In this example, the
pass
keyword is used to define a custom exception that does not have any additional code or behavior.The
pass
keyword is a useful tool for ensuring that your code runs without errors while you are still developing or testing certain parts of your program. However, you should be careful not to usepass
excessively or in situations where it is not necessary, as it can make your code difficult to read and understand.The return Keyword:
- In a loop where you want to do nothing for a certain iteration:
The return
keyword in Python is used to exit a function and return a value to the caller. It can be used in a function to specify the value that should be returned when the function is called.
Here’s an example to illustrate the use of the return
keyword:
def add_numbers(a, b): sum = a + b return sum result = add_numbers(3, 4) print(result)
In this example, the add_numbers
function takes two arguments a
and b
and adds them together to get the sum. The return
statement is used to return the value of sum
to the caller. When the function is called with arguments 3 and 4, it returns the value 7, which is then assigned to the variable result
. The print
statement is used to print the value of result
, which is 7.
The return
keyword can also be used to return multiple values from a function by separating them with commas, which creates a tuple:
def get_info(): name = "John" age = 30 address = "123 Main St" return name, age, address result = get_info() print(result)
In this example, the get_info
function returns three values name
, age
, and address
. When the function is called, it returns these values as a tuple, which is then assigned to the variable result
. The print
statement is used to print the value of result
, which is ('John', 30, '123 Main St')
.
The return
keyword is a powerful tool in Python that allows you to exit a function and return a value to the caller. It is essential in many programming tasks and is used frequently in Python code.
The del Keyword:
The del
keyword in Python is used to delete a variable or an item from a data structure like a list or dictionary. It can also be used to delete a reference to an object.
Here are some examples to illustrate the use of the del
keyword:
- Deleting a variable:
x = 5 del x
In this example, the variable x
is assigned the value 5, and the del
keyword is used to delete it. After executing del x
, the variable x
no longer exists in memory.
- Deleting an item from a list:
my_list = [1, 2, 3, 4] del my_list[2]
In this example, the del
keyword is used to delete the third item from the list my_list
. After executing del my_list[2]
, the list becomes [1, 2, 4]
.
- Deleting a key-value pair from a dictionary:
my_dict = {'name': 'John', 'age': 30, 'address': '123 Main St'} del my_dict['age']
In this example, the del
keyword is used to delete the key-value pair with the key age
from the dictionary my_dict
. After executing del my_dict['age']
, the dictionary becomes {'name': 'John', 'address': '123 Main St'}
.
The del
keyword can also be used to delete a reference to an object. When an object is no longer referenced by any variable, it is automatically deleted by Python’s garbage collector.
In summary, the del
keyword in Python is used to delete variables, items from data structures, key-value pairs from dictionaries, and references to objects. It is a powerful tool that can be used to manage memory and remove unwanted data from your programs.