Skip to main content

Python Keyword List

Keywords are the reserved words in Python. You can not use a keyword as a variable name, function name or any other identifier.

How to Get List of Keywords of your Python version

Different versions of Python may have different keywords.

You can always get the list of keywords in your current version by typing the following in the prompt.

import keyword
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']

Keywords

KeywordDescription
andA logical operator
asTo create an alias
assertFor debugging
asyncTo mark a function as a coroutine, enabling its execution to be paused and resumed, facilitating asynchronous programming
awaitTo pauses the execution of a coroutine until an awaited object is ready
breakTo break out of a loop
classTo define a class
continueTo continue to the next iteration of a loop
defTo define a function
delTo delete an object
elifUsed in conditional statements, same as else if
elseUsed in conditional statements
exceptUsed with exceptions, what to do when an exception occurs
FalseBoolean value, result of comparison operations
finallyUsed with exceptions, a block of code that will be executed no matter if there is an exception or not
forTo create a for loop
fromTo import specific parts of a module
globalTo declare a global variable
ifTo make a conditional statement
importTo import a module
inTo check if a value is present in a list, tuple, etc.
isTo test if two variables are equal
lambdaTo create an anonymous function
NoneRepresents a null value
nonlocalTo declare a non-local variable
notA logical operator
orA logical operator
passA null statement, a statement that will do nothing
raiseTo raise an exception
returnTo exit a function and return a value
TrueBoolean value, result of comparison operations
tryTo make a try...except statement
whileTo create a while loop
withUsed to simplify exception handling
yieldTo return a list of values from a generator

and

The and keyword is a logical operator in Python: it will return True only if both the operands are True.

Truth table for and logical operator is given below:

ABA and B
TrueTrueTrue
TrueFalseFalse
FalseTrueFalse
FalseFalseFalse

Example demonstrating the use of and operator:

print(True and True)   # Output: True
print(True and False) # Output: False
print(False and True) # Output: False
print(False and False) # Output: False

output

True
False
False
False
note

To learn more about booleans and logic operators, visit Python Boolean.

as

The as keyword is used to create an alias for a module while importing it.

This allows you to give a different name to a module, which can be particularly useful to avoid naming conflicts or to make the code more readable.

For example, Python has a standard module called math. If you want to use this module but prefer to refer to it with a different name, you can do so using the as keyword.

Here's how you can import the math module with an alias named myAlias:

import math as myAlias

result = myAlias.cos(myAlias.pi)
print(result) # Output: -1.0

output

-1.0

assert

The assert keyword is used for debugging purposes.

It allows you to test if a certain condition is met and if not, it raises an AssertionError. This can be particularly useful for checking assumptions in your code and finding bugs more conveniently.

The syntax of assert is the following:

assert condition, message

where:

  • condition is the condition that you want to test.
    • If the condition evaluates to True, the program continues to execute normally.
  • message is an optional argument.
    • If the condition is False, an AssertionError will be raised with the provided message.
    • If no message is provided, the error message will be the string representation of the condition that failed.

For example, here we want to assert if a is smaller than 5:

a = 10
assert a < 5, "The value of a is too large"

output

Traceback (most recent call last):
File "main.py", line 2, in <module>
assert a < 5, "The value of a is too large"
AssertionError: The value of a is too large
note
assert condition, message

is equivalent to

if not condition:
raise AssertionError(message)

async

The async keyword is used to define a function as a coroutine.

A coroutine is a special type of function that can be paused and resumed, allowing other code to run in the meantime.

note

The async keyword is provided by the asyncio library in Python.

For example, here:

  • main is an asynchronous function defined with async.
  • Inside main, asyncio.sleep(1) is used to simulate a delay.
  • The await keyword is used to pause the execution of main until asyncio.sleep(1) completes. During this pause, the event loop can execute other tasks. After the sleep completes, the function resumes, and 'world' is printed.
import asyncio

async def main():
print('Hello')
await asyncio.sleep(1) # Simulate a delay
print('world')

# To run the coroutine, use asyncio.run()
asyncio.run(main())

await

The await keyword is used within an async function to pause the execution of the function until the awaited coroutine is complete. In other words, await is used to wait for the result of a coroutine without blocking the entire program.

For example, here:

  • main is an asynchronous function defined with async.
  • Inside main, asyncio.sleep(1) is used to simulate a delay.
  • The await keyword is used to pause the execution of main until asyncio.sleep(1) completes. During this pause, the event loop can execute other tasks. After the sleep completes, the function resumes, and 'world' is printed.
import asyncio

async def main():
print('Hello')
await asyncio.sleep(1) # Simulate a delay
print('world')

# To run the coroutine, use asyncio.run()
asyncio.run(main())

break

The break keyword is used to exit the current loop prematurely and it can be used in both for and while loops to alter their normal behavior.

When a break statement is encountered, the loop is immediately terminated, and control flows to the statement immediately following the loop.

Example of break in a for loop: when variable i becomes equal to 5, the break statement is executed, and the loop is terminated.

for i in range(1, 11):
if i == 5:
break
print(i)

output

1
2
3
4

Example of break in a while loop: when variable i becomes equal to 5, the break statement is executed, and the loop is terminated.

i = 1
while i < 11:
if i == 5:
break
print(i)
i = i + 1

output

1
2
3
4
note

To learn more about break statement, visit Python break Statement.

class

The class keyword is used to define a new user-defined class.

A class is like a blueprint for creating objects, providing initial values for state (attributes), and implementations of behavior (methods).

For example:

class ExampleClass:
def function1(self, parameters):
# Implementation of function1
pass

def function2(self, parameters):
# Implementation of function2
pass
note

Classes can be defined anywhere in a program. But it is a good practice to define a single class in a module.

note

To learn more about class and objects, visit Python Class and Objects.

continue

The continue keyword is used in for and while loops to skip the rest of the current iteration and move on to the next iteration of the loop.

note

When the continue statement is encountered, the loop immediately jumps to the beginning of the next iteration, effectively skipping any code that follows the continue statement within the loop body.

For example, the continue statement in a for loop.

  • Here, the for loop is intended to print numbers from 1 to 10. However, when i equals 5, the continue statement is executed, causing the loop to skip the rest of the current iteration and proceed to the next iteration.
for i in range(1, 11):
if i == 5:
continue
print(i)

output

1
2
3
4
6
7
8
9
10
note

To learn more about continue statement, visit Python continue Statement.

def

The def keyword is used to define a function.

A function is a block of organized, reusable code that performs a specific task. Functions help break our program into smaller and modular chunks. As our program grows larger, functions make it more organized and manageable.

Here's the basic syntax for defining a function using the def keyword:

def function_name(parameters):
# function body
pass

where:

  • function_name: This is the name of the function. It can be any valid identifier.
  • parameters: These are optional. Parameters are listed inside parentheses after the function name. They are used to pass values into a function. Parameters are defined by data type followed by the variable name.
note

To learn more about functions, visit Python Functions.

del

The del keyword is used to delete the reference to an object.

Since everything in Python is an object (variables, lists, dictionaries, etc.) del keyword can be used to remove references to these objects, effectively deleting them from memory and freeing up memory space.

a = b = 5
del a
print(b) # Output: 5 (because 'b' was not deleted)
print(a) # Raises NameError because 'a' is no longer defined

output

5
Traceback (most recent call last):
File "main.py", line 4, in <module>
print(a) # Raises NameError because 'a' is no longer defined
NameError: name 'a' is not defined

del can also be used to remove elements from lists

my_list = ['x', 'y', 'z']
del my_list[1] # Removes the element at index 1 (i.e. 'y')
print(my_list) # Output: ['x', 'z']

output

['x', 'z']

or keys from dictionaries:

my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
del my_dict['key1'] # Removes the key-value pair
print(my_dict) # Output: {'key2': 'value2', 'key3': 'value3'}

output

{'key2': 'value2', 'key3': 'value3'}

elif

The elif keyword stands for "else if" and it is used together with if and else statements.

The elif statement allows you to execute a block of code if the conditional expressions evaluate to True.

For example:

def if_example(a):
if a == 1: # if statemenet
print('One')
elif a == 2: # elif statement
print('Two')
else: # else statement
print('Something else')

if_example(1)
if_example(2)
if_example(3)

output

One
Two
Something else
note

To learn more about elif statement, visit Python if Statement.

else

The else keyword is used together with if and elif statements.

The block of code defined fot else statement is executed when all of preceding conditions of if and elif are evaluated to False.

For example:

def if_else_example(a):
if a > 0: # if statemenet
print('Positive')
elif a == 0: # elif statement
print('Zero')
else: # else statement
print('Negative')

if_else_example(5)
if_else_example(0)
if_else_example(-3)

output

Positive
Zero
Negative
note

To learn more about else statement, visit Python if Statement.

except

The except keyword is used together with try to catch and handle exceptions.

The except block lets you handle the exception and decide what to do next.

note

An exception is an event that occurs during the execution of programs that disrupts the normal flow of instructions. When an error occurs or a particular condition is met in your program, Python raises an exception.

For example:

try:
# Code that may raise an exception
result = 10 / 0
except ZeroDivisionError:
# Block of code to handle the exception
print("Can not divide by zero")

output

Can not divide by zero
note

To learn more about except statement, visit Python Exception Handling.

False

The False keyword is a boolean literal representing the Boolean value False

It is used in conditional expressions and loops to represent truth values: a condition is not met or that a statement is false.

if False:
print("This won't be printed.")
else:
print("This will be printed.")

output

This will be printed.

Moreover, False can be a result of comparison operations or logical operations:

print(10 <= 1)          # Output: False
print(3 > 7) # Output: False
print(True and False) # Output: False
note

To learn more about booleans and logic operators, visit Python Boolean.

finally

The finally keyword is used together with try and except to ensure that a block of code is executed no matter what happens in the try...except block.

note

An exception is an event that occurs during the execution of programs that disrupts the normal flow of instructions. When an error occurs or a particular condition is met in your program, Python raises an exception.

This is particularly useful for cleanup actions that must be completed regardless of whether an exception was raised or not.

try:
# Code that may raise an exception
pass
except MyException:
# Handle MyException
pass
finally:
# Cleanup code that runs regardless of exceptions
pass

For example, read content of a file and finally close the file regardless of whether an exception occurs:

file = open('example.txt', 'r')
try:
content = file.read()
# Process content
except IOError:
print("IOError occurred")
finally:
file.close() # Ensures the file is closed regardless of success or failure
note

To learn more about finally statement, visit Python Exception Handling.

for

The for keyword is used to iterate over a sequence (list, tuple, dictionary, set, string).

It allows you to execute a block of code for each item in the sequence.

The syntax of a for loop involves specifying a target variable that will hold the current item in each iteration of the loop, followed by the sequence to iterate over.

For example:

names = ['Tom', 'Dave', 'Anna', 'Ryan']
for name in names:
print('Hello ' + name)

output

Hello Tom
Hello Dave
Hello Anna
Hello Ryan
note

To learn more about for loop, visit Python For Loop.

from

The from keyword is used together with import to import specific attributes or functions from a module into the current namespace, rather than importing the entire module.

This allows you to use those imported entities directly without prefixing them with the module name.

Here's an example to illustrate how from... import works:

from math import sqrt

# Use the sqrt function directly
result = sqrt(16)
print(result) # Output: 4.0

output

4.0
note

To learn more about modules, visit Python Modules.

global

The global keyword is used to declare that a variable inside a function is global, meaning it is accessible throughout the entire program, not just within the function where it is defined.

note

This is particularly useful when you need to modify a variable that is defined outside of the function.

Here's an example to illustrate the use of the global keyword:

globvar = 10

def read1():
print(globvar)

def write1():
global globvar
globvar = 5

def write2():
globvar = 15

read1()
write1()
read1()
write2()
read1()

output

10
5
5
note

To learn more about global variables, visit Python Global, Local and Non-local Variables.

if

The if keyword is used for conditional branching or decision making.

It allows you to test a condition and execute a block of code only if the condition evaluates to True. Moreover, it can be used together with else and elif statements.

number = 15
if number > 10:
print("Number is greater than 10.")
else:
print("Number is not greater than 10.")

output

Number is greater than 10.
note

To learn more about if statement, visit Python if Statement.

import

The import keyword is used to load external modules into the current namespace, allowing you to use the functions, classes, and variables defined in those modules.

Here's a basic example of how to use the import keyword:

import math

# Use the sin function from the math module
angle_in_radians = math.pi / 2
sin_result = math.sin(angle_in_radians)
print(sin_result) # Output: 1.0

output

1.0
note

To learn more about modules, visit Python Modules.

in

The in keyword is used in two cases:

  • checking membership in sequences
  • iterating over sequences in loops

In checking membership, the in keyword is used to test if a value is present in a sequence (like a list, tuple, string, etc.).

It returns True if the value is found in the sequence, otherwise, it returns False. Here's an example:

a = [1, 2, 3, 4, 5]
print(5 in a) # Output: True
print(10 in a) # Output: False

In iterating over sequences, the in keyword is used in for loops to iterate over a sequence object. Here's how it's used with a string:

for i in 'hello':
print(i)

output

h
e
l
l
o

is

The is keyword is used to test object identity, which means it checks if two variables refer to the exact same object in memory.

note

Unlike the equality operator ==, which checks if two variables have the same value, is keyword checks if they are the same object.

Here are some examples to illustrate the difference between == and is:

# Using ==
print([] == []) # Output: True
print({} == {}) # Output: True

# Using is
print([] is []) # Output: False
print({} is {}) # Output: False

Immutable objects, such as tuples and strings, behave differently due to their nature: is returns True because there is only one instance of each in memory. For example:

print(('') is '')  # Output: True
print((()) is ()) # Output: True

lambda

The lambda keyword is used to create anonymous functions.

  • A lambda function can take any number of arguments but can only have one expression. The expression is evaluated and returned.
  • Lambda functions can be used wherever function objects are required.
  • Lambda functions are particularly useful for short, throwaway functions that don't warrant a full definition.

Here's a simple example of a lambda function that takes two arguments and returns their sum:

sum = lambda a, b: a + b
print(sum(5, 3)) # Output: 8
note

To learn more about Lambdas statement, visit Python Lambda and Anonymous Functions.

None

The None keyword represents the absence of a value or a null value.

note

It is a special constant belonging to its own datatype, NoneType.

Unlike other types, there is only one instance of None, and it is immutable. So you can assign it to variables but you can not create multiple instances of it.

Void functions that do not return anything will return a None object automatically. Moreover, None is returned by functions in which the program flow does not encounter a return statement.

def calculate_sum(a, b):
total = a + b
# No return statement, so None is returned implicitly

result = calculate_sum(5, 7)
print(result) # Output: None

output

None

Special care must be taken because that None does not imply False, 0 or any empty list, dictionary, string etc. For example:

print(None == 0)     # Output: False
print(None == []) # Output: False
print(None == False) # Output: False

x = None
y = None
print(x == y) # Output: true

nonlocal

The nonlocal keyword is used in nested functions to indicate that a variable should refer to a variable in the nearest enclosing scope that is not global. Essentially, nonlocal allows a nested function to modify variables that belong to an enclosing function, but not globally.

def outer_function():
x = 'local' # x is local to outer_function
def inner_function():
nonlocal x # Declares x is not local to inner_function
x = 'nonlocal' # Modifies the x from outer_function
print("Inner function: ", x)
inner_function() # Calls inner_function
print("Outer function: ", x) # Prints the modified x from outer_function

outer_function() # Outputs: 'nonlocal'

output

nonlocal
note

To learn more about nonlocal variables, visit Python Global, Local and Non-local Variables.

not

The not keyword is a logical operator in Python.

It will return True if the operand is False, and False if the operand is True.

Truth table for not logical operator is given below:

Anot A
TrueFalse
FalseTrue

Example demonstrating the use of not operator:

print(not True)   # Output: False
print(not False) # Output: True

output

False
True
note

To learn more about booleans and logic operators, visit Python Boolean.

or

The or keyword is a logical operator in Python.

It will return True if at least one of the operands is True. If both operands are False, then it returns False.

Truth table for or logical operator is given below:

ABA or B
TrueTrueTrue
TrueFalseTrue
FalseTrueTrue
FalseFalseFalse

Example demonstrating the use of or operator:

print(True or True)   # Output: True
print(True or False) # Output: True
print(False or True) # Output: True
print(False or False) # Output: False

output

True
True
True
False
note

To learn more about booleans and logic operators, visit Python Boolean.

pass

The pass keyword is used as a placeholder statement that allows syntactically correct programs to be written before they are completed. In other words, pass acts as a null statement that does nothing.

For example, if you are defining a class or a function but you have not implemented its functionality yet, using pass prevents the interpreter from raising an indentation error due to missing blocks of code.

def my_function(arg1, arg2):
pass
class MyClass:
pass

raise

The raise keyword is used to trigger an exception manually within a program.

note

When an exception is raised, the normal flow of the program is interrupted, and control is transferred to the nearest enclosing try block that can handle the exception.

For example:

def validate_age(age):
if age < 18:
raise ValueError("Age must be 18 or older")
else:
return True

try:
validate_age(17)
except ValueError as ve:
print(ve)
note

To learn more about raise statement, visit Python User-defined Exceptions.

return

The return keyword is used to specify the result that a function should return to the caller.

When a function encounters a return statement, it immediately exits and gives back the specified value. If no value is specified, the function returns None by default.

For example:

def func_with_return():
a = 123
return a

def func_without_return():
a = 123

print(func_with_return())
print(func_without_return())

output

123
None

True

The True keyword is a boolean literal representing the Boolean value True

It is used in conditional expressions and loops to represent truth values: a condition is met or that a statement is true.

if True:
print("This will be printed.")
else:
print("This won't be printed.")

output

This will be printed.

Moreover, True can be a result of comparison operations or logical operations:

print(1 == 1)          # Output: True
print(5 > 3) # Output: True
print(True or False) # Output: True
note

Learn more about booleans and logic operators, visit Python Boolean.

try

The try keyword is used together with except to catch and handle exceptions.

note

An exception is an event that occurs during the execution of programs that disrupts the normal flow of instructions. When an error occurs or a particular condition is met in your program, Python raises an exception.

The try block contains code that might throw an exception, while the except block contains code that handles the exception if one occurs.

Here's a basic structure of how try and except are used together:

try:
# Code that might raise an exception
result = 10 / 0
except ZeroDivisionError:
# Code to handle the exception
print("Can not divide by zero")

output

Can not divide by zero
note

To learn more about try statement, visit Python Exception Handling.

while

The while keyword is used to create a loop that continues executing its block of code as long as the given condition remains True.

note

The while loop checks the condition before entering the loop. If the condition is True, the loop starts executing; otherwise, it skips the loop entirely.

Here's a basic example of how the while loop works:

i = 0
while i < 5:
print(i)
i = i + 1

output

0
1
2
3
4
note

To learn more about while loop, visit Python While Loop.

with

The with keyword is used in exception handling to wrap the execution of a block of code within methods defined by a context manager.

Context managers allow common try-except-finally usage patterns to be encapsulated for convenient reuse: the with statement ensures proper resource management by automatically acquiring and releasing resources, such as file handles, network connections, or locks, regardless of whether exceptions occur within the block.

A context manager is an object that defines the methods __enter__() and __exit__(); these methods manage the setup and teardown of the context. When the with statement is encountered, the __enter__() method is called, setting up the context. After the block of code is executed, the __exit__() method is called, cleaning up the context.

Here's a simple example demonstrating the use of with for managing file access:

with open('example.txt', 'r') as file:
content = file.read()

print(content)

yield

The yield keyword is used inside a function like a return statement, but instead of returning a single value and terminating the function, yield produces a generator.

note

Generators are a type of iterator that generate values on-the-fly, rather than storing them in memory.

By using yield, a function becomes a generator function, and calling it creates a generator object. This object can then be iterated over using a for loop or other iteration constructs, with each call to the generator's __next__() method (or the built-in next() function) producing the next value in the sequence until the generator is exhausted.

Here's a simple example to illustrate how yield works:

def count_up_to(max):
count = 1
while count <= max:
yield count
count += 1

counter = count_up_to(5)
for number in counter:
print(number)

output

1
2
3
4
5