Python Keywords List with uses and examples
Python Keywords are the backbone of this versatile language. My in-depth article explores their significance and empowers you to code with confidence.
Python keywords refer to the set of reserved words in the Python programming language that are used to define specific instructions and functions. These keywords have predefined meanings and cannot be used as variable names or identifiers.
Python Keywords List
As of Python 3.10, there are 35 keywords in Python. These keywords are reserved and cannot be used as variable names or function names in a Python program.
๐ก Complete Python Roadmap for beginners and experts.
Below is the table for all 35 keywords with their short description. To get more details about the keyword, click on the keyword name in the table.
Keyword | Description |
False | A boolean value representing false. |
None | Represents the absence of a value. |
True | A boolean value representing true. |
and | A logical operator that returns true if both operands are true. |
as | Used to create an alias for a module or module object. |
assert | Used for debugging purposes to check if a condition is true. |
async | Used to define an asynchronous function. |
await | Used to wait for an asynchronous function to complete. |
break | Used to exit a loop prematurely. |
class | Used to define a class. |
continue | Used to skip the current iteration of a loop. |
def | Used to define a function. |
del | Used to delete a reference to an object. |
elif | Used in an if-elif-else statement to test multiple conditions. |
else | Used in an if-elif-else statement to define the else clause. |
except | Used in a try-except block to catch and handle exceptions. |
finally | Used in a try-except-finally block to define the finally clause. |
for | Used to iterate over a sequence. |
from | Used to import specific attributes or functions from a module. |
global | Used to define a global variable inside a function. |
if | Used to test a condition. |
import | Used to import a module. |
in | Used to test if a value is a member of a sequence. |
is | Used to test if two objects are the same. |
lambda | Used to define a small anonymous function. |
nonlocal | Used to define a variable in the nearest enclosing scope. |
not | A logical operator that returns true if the operand is false. |
or | A logical operator that returns true if at least one operand is true. |
pass | A null operation used as a placeholder. |
raise | Used to raise an exception. |
return | Used to return a value from a function. |
try | Used to enclose code that might raise an exception. |
while | Used to create a loop that executes as long as a condition is true. |
with | Used to create a context manager. |
yield | Used in a generator function to produce a value for iteration. |
You can get a list of keywords in your system by using the command
help("keywords")
๐ก Bookmark this Python Syntax Cheatsheet.
Types of Keywords
In Python, there are 8 categories in which Python keywords can be grouped:
Control flow statements
These are the keywords that are used to control the flow of execution in a program. They include:
if, else, elif: Used for conditional branching.
while, for: Used for loops.
break, continue: Used to break out of a loop or skip an iteration.
return: Used to return a value from a function.
Function and class definition
These are the keywords used to define functions and classes. They include:
def: Used to define a function.
class: Used to define a class.
Variable and scope modifiers
These are the keywords used to modify the scope and behavior of variables. They include:
global: Used to define a global variable.
nonlocal: Used to access a variable in an enclosing function's scope.
lambda: Used to define anonymous functions.
Exception handling
These are the keywords used to handle exceptions in Python. They include:
try, except, finally: Used for exception handling.
raise: Used to raise an exception.
Import and module usage
These are the keywords used to import modules and use them in Python. They include:
import: Used to import a module.
from: Used to import specific parts of a module.
as: Used to alias a module or variable name.
Boolean and identity operators
These are the keywords used to perform logical operations in Python. They include:
and, or, not: Used for Boolean operations.
is, is not: Used for identity testing.
Numerical and string operations
These are the keywords used to perform numerical and string operations in Python. They include:
in, not in: Used for membership testing.
True, False, None: Used to represent Boolean values.
yield: Used in generators to return a value.
Miscellaneous
These are the keywords that don't fit into any of the above categories. They include:
assert: Used for debugging purposes.
pass: Used as a placeholder in empty code blocks.
del: Used to delete a variable or object.
Keywords Use with Example
False Keyword
A boolean value that represents false. It is often used in boolean expressions and comparisons. For example:
x = 5
y = 10
print(x < y) # True
print(x > y) # False
None Keyword
A singleton object that represents the absence of a value. It is often used to indicate that a variable has not been initialized or that a function does not return a value. For example:
x = None
def foo():
print("Hello, world!")
result = foo() # prints "Hello, world!"
print(result) # None
True Keyword
A boolean value that represents true. Like False, it is often used in boolean expressions and comparisons. For example:
x = 5
y = 10
print(x == 5 and y == 10) # True
print(x == 10 or y == 5) # False
And Keyword
A logical operator that performs a logical AND operation on two boolean values. It returns True if both values are true and False otherwise. For example:
x = 5
y = 10
z = 15
print(x < y and y < z) # True
print(x < y and y > z) # False
As Keyword
A keyword used to create an alias for a module or import statement. It can also be used to assign a new name to an object in a with statement. For example:
import numpy as np
with open('file.txt', 'r') as f:
contents = f.read()
Assert keyword
A debugging aid that tests a condition and raises an error if the condition is not true. It is often used to check the correctness of code during development. For example:
x = 5
y = 10
assert x < y, "x is not less than y"
Async Keyword
A keyword used to define a coroutine function, which allows for asynchronous programming. It must be used in conjunction with await. For example:
async def foo():
await asyncio.sleep(1)
print("Hello, world!")
Await Keyword
A keyword used to pause the execution of a coroutine until a future completes. It can only be used inside a coroutine function that is decorated with async. For example:
async def foo():
await asyncio.sleep(1)
print("Hello, world!")
Break Keyword
A keyword used to exit a loop prematurely. It is often used in conjunction with a conditional statement to exit a loop when a certain condition is met. For example:
for i in range(10):
if i == 5:
break
print(i)
Class Keyword
A keyword used to define a class in object-oriented programming. It is followed by the class name and a colon. For example:
class MyClass:
pass
Continue Keyword
A keyword used to skip the current iteration of a loop and move on to the next iteration. It is often used in conjunction with a conditional statement to skip certain iterations of a loop. For example:
for i in range(10):
if i % 2 == 0:
continue
print(i)
Def Keyword
A keyword used to define a function. It is followed by the function name, parentheses, and a colon. For example:
def my_function():
print("Hello, world!")
Del Keyword
A keyword used to delete an object or attribute. It can be used to remove an item from a list, delete a variable, or remove a key-value pair from a dictionary. For example:
my_list = [1, 2, 3]
del my_list[1]
print(my_list) # [1, 3]
x = 5
del x
my_dict = {'a': 1, 'b': 2}
del my_dict['a']
print(my_dict) # {'b': 2}
Elif Keyword
A keyword used in conditional statements to check for additional conditions after an initial if statement. It is often used in conjunction with if and else. For example:
x = 5
if x < 5:
print("x is less than 5")
elif x == 5:
print("x is equal to 5")
else:
print("x is greater than 5")
Else Keyword
A keyword used to define the alternative branch in an if statement. It is executed when the condition in the if statement is false. For example:
x = 5
if x == 10:
print("x is 10")
else:
print("x is not 10")
Except Keyword
A keyword used to catch an exception in a try-except block. It is followed by the type of exception to catch. For example:
try:
x = 1 / 0
except ZeroDivisionError:
print("Error: division by zero")
Finally Keyword
A keyword used in a try-except block to define a block of code that is always executed, regardless of whether an exception was raised or not. For example:
try:
x = 1 / 0
except ZeroDivisionError:
print("Error: division by zero")
finally:
print("This code is always executed")
For Keyword
A keyword used to create a for loop. It is followed by a variable name, the keyword in, and an iterable object. For example:
for i in range(10):
print(i)
From Keyword
A keyword used to import a specific function or attribute from a module. For example:
from math import sqrt
print(sqrt(4))
Global Keyword
A keyword used to access a global variable inside a function. It is used to indicate that a variable should be treated as a global variable, rather than a local variable. For example:
x = 5
def foo():
global x
x = 10
foo()
print(x) # 10
If Keyword
A keyword used to create an if statement. It is followed by a condition in parentheses and a colon. For example:
x = 5
if x == 5:
print("x is 5")
Import Keyword
A keyword used to import a module. It is followed by the name of the module. For example:
import math
print(math.sqrt(4))
In Keyword
A keyword used to test whether an element is present in a sequence. It is often used in for loops and if statements. For example:
x = [1, 2, 3, 4, 5]
if 3 in x:
print("3 is in x")
Is Keyword
A keyword used to test whether two variables refer to the same object. It is often used to compare objects, especially when dealing with mutable objects like lists and dictionaries. For example:
x = [1, 2, 3]
y = [1, 2, 3]
if x is y:
print("x and y refer to the same object")
else:
print("x and y are different objects")
Lambda Keyword
A keyword used to define an anonymous function. It is followed by the arguments in parentheses and a colon, and the function body. For example:
add = lambda x, y: x + y
print(add(3, 4)) # 7
Nonlocal Keyword
A keyword used to refer to a variable in the nearest enclosing scope, excluding the global scope. This is useful when you have nested functions and you want to access or modify a variable in an outer function's scope. For example:
def outer_function():
x = 5
def inner_function():
nonlocal x
x += 1
print(x)
inner_function()
print(x)
outer_function()
Not Keyword
A keyword used to negate a boolean expression. It is often used in if statements and while loops. For example:
x = 5
if not x == 6:
print("x is not 6")
Or Keyword
A keyword used to perform a logical OR operation between two boolean expressions. It returns True if at least one of the expressions is True. For example:
x = 5
if x == 5 or x == 6:
print("x is either 5 or 6")
Pass Keyword
A keyword used to create an empty block of code. It is often used as a placeholder in functions or classes that are not yet implemented. For example:
def foo():
pass
Raise Keyword
A keyword used to raise an exception in a try-except block. It is followed by the type of exception to raise. For example:
def divide(x, y):
if y == 0:
raise ZeroDivisionError("Cannot divide by zero")
return x / y
try:
result = divide(10, 0)
except ZeroDivisionError as error:
print(error)
Return Keyword
A keyword used to return a value from a function. It is followed by the value to be returned. For example:
def add(x, y):
return x + y
print(add(3, 4)) # 7
Try Keyword
A keyword used to create a try-except block. It is followed by a block of code that may raise an exception. For example:
try:
x = 1 / 0
except ZeroDivisionError:
print("Error: division by zero")
While Keyword
A keyword used to create a while loop. It is followed by a condition in parentheses and a colon. For example:
x = 0
while x < 10:
print(x)
x += 1
With Keyword
A keyword used to create a context manager. It is often used with files and other resources that need to be opened and closed. For example:
with open("file.txt", "r") as f:
print(f.read())
Yield Keyword
A keyword used to create a generator function. It is followed by the value to yield. For example:
def my_range(start, end):
current = start
while current < end:
yield current
current += 1
for i in my_range(0, 5):
print(i)
๐ก [Optional] Refer to install python and virtual environment guide.
In conclusion, keywords are an integral part of Python programming language. Understanding their types and usage is crucial for writing efficient and error-free code. It's important to note that you should not use reserved and special keywords as variable names or identifiers in your Python code. Doing so will result in a syntax error. With practice, you can become proficient in using these keywords to build powerful and robust applications.