Python's Reserved Keywords

Python has a set of reserved words known as keywords, which are used by the Python interpreter for specific functionality. These words have special meaning in Python syntax and cannot be used as variable names, function names, or identifiers. In this guide, we'll cover the complete list of Python keywords and their uses.


Python Reserved Keywords

The following is a list of all reserved keywords in Python. These keywords are part of the Python language syntax and serve specific purposes:

andasassertasyncawait
breakclasscontinuedefdel
elifelseexceptFalsefinally
forfromglobalifimport
inislambdanonlocalnot
Noneorpassraisereturn
Truetrywhilewithyield

These are the keywords in Python as of the latest version. You cannot use any of these as identifiers (such as variable names or function names).

1. and

The and keyword is used to check if two or more conditions are all true. If every condition is true, the whole expression is true.

This is useful when you want to make sure that multiple things are correct before running some code.

Common uses:

  • Checking multiple conditions in an if statement.
  • Making your code more specific and accurate.

In the example below, the program checks whether both numbers are greater than 0:

python
x = 5
y = 10

if x > 0 and y > 0:
    print("Both numbers are positive")  # Output: Both numbers are positive

2. as

The as keyword is used to give a different name (an alias) to something, usually when importing a module.

This is useful when the original name is long or if you want to use a shorter or clearer name in your code.

Common uses:

  • Importing a module using a short alias.
  • Handling exceptions with a custom variable name.

In the example below, we import the math module using as to give it a shorter name:

python
import math as m

print(m.sqrt(16))  # Output: 4.0

3. assert

The assert keyword is used to test if a condition is true. If it’s not, the program will stop and show an error.

This is useful for finding bugs early by making sure certain conditions are met while your code runs.

Common uses:

  • Checking that values are what you expect them to be.
  • Stopping the program if something is wrong.

In the example below, we make sure that the value of x is positive:

python
x = 5
assert x > 0  # Passes, because x is greater than 0

# If x were negative, this would raise an AssertionError

4. async

The async keyword is used to define a special kind of function that runs in the background and doesn't block your program.

This is useful when you're doing tasks that take time, like downloading data or waiting for a response from a server.

Common uses:

  • Creating asynchronous functions that can pause and resume.
  • Improving performance by not waiting for slow tasks.

In the example below, we define an async function that waits for 1 second before printing a message:

python
import asyncio

async def say_hello():
    print("Hello...")
    await asyncio.sleep(1)
    print("...world!")

# To run this, use: asyncio.run(say_hello())

5. await

The await keyword is used inside an async function to pause the function until something finishes, like waiting for a timer.

This helps your program do other things instead of stopping completely while waiting.

Common uses:

  • Pausing an async function while a slow task finishes.
  • Used only inside functions defined with async.

In the example below, the program waits 2 seconds before continuing:

python
import asyncio

async def wait_and_print():
    print("Waiting...")
    await asyncio.sleep(2)
    print("Done!")

# To run this, use: asyncio.run(wait_and_print())

6. break

The break keyword is used to exit from a loop, such as a for or while loop, even if the loop condition is still true.

This is useful when you want to stop the loop early, often when a specific condition is met.

Common uses:

  • Exiting a loop early when a condition is met.
  • Ending an infinite loop when a certain event happens.

In the example below, the loop breaks when we find the number 3:

python
for num in range(5):
    if num == 3:
        break
    print(num)  # Output: 0, 1, 2

7. class

The class keyword is used to define a new class in Python, which is a blueprint for creating objects with specific attributes and methods.

This is useful when you want to bundle data and functionality together in a single unit.

Common uses:

  • Creating custom data structures.
  • Defining objects with specific behavior and properties.

In the example below, we define a class called Dog and create an object of that class:

python
class Dog:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def bark(self):
        print("Woof!")

my_dog = Dog("Buddy", 3)
my_dog.bark()  # Output: Woof!

8. continue

The continue keyword is used to skip the current iteration of a loop and move to the next iteration.

This is useful when you want to skip specific conditions or values within a loop without breaking the loop completely.

Common uses:

  • Skipping unwanted values in a loop.
  • Continuing with the next iteration when a condition is met.

In the example below, we skip printing the number 3:

python
for num in range(5):
    if num == 3:
        continue
    print(num)  # Output: 0, 1, 2, 4

9. def

The def keyword is used to define a function in Python. Functions allow you to group reusable code under a specific name.

This is useful when you want to execute a set of instructions multiple times with different inputs.

Common uses:

  • Creating reusable blocks of code (functions).
  • Improving code organization and readability.

In the example below, we define a function that adds two numbers together:

python
def add(a, b):
    return a + b

result = add(3, 4)
print(result)  # Output: 7

10. del

The del keyword is used to delete a variable, list item, or attribute in Python.

This is useful when you want to remove something from memory or clear data that you no longer need.

Common uses:

  • Removing items from a list.
  • Deleting variables or attributes to free up memory.

In the example below, we delete an item from a list:

python
my_list = [1, 2, 3, 4]
del my_list[2]

print(my_list)  # Output: [1, 2, 4]

11. elif

The elif keyword is used to add additional conditions in an if statement. It stands for "else if" and allows you to check multiple conditions.

This is useful when you want to test more than one condition and take different actions depending on which condition is true.

Common uses:

  • Adding extra conditions in an if statement.
  • Making your code more flexible and readable.

In the example below, the program checks for different ranges of numbers:

python
x = 10

if x < 5:
    print("x is less than 5")
elif x == 10:
    print("x is equal to 10")  # Output: x is equal to 10

12. else

The else keyword is used to define a block of code that will run when all previous conditions in an if or elif statement are false.

This is useful when you want to specify what should happen when no conditions are true.

Common uses:

  • Providing an alternative action when conditions fail.
  • Handling the "default" case in conditional structures.

In the example below, the program will print a message when the number is neither less than nor equal to 10:

python
x = 15

if x < 10:
    print("x is less than 10")
else:
    print("x is greater than or equal to 10")  # Output: x is greater than or equal to 10

13. except

The except keyword is used in a try-except block to handle exceptions (errors) that occur during program execution.

This is useful when you want to handle specific errors gracefully and continue running the program instead of crashing.

Common uses:

  • Handling errors without stopping the program.
  • Specifying different actions for different types of exceptions.

In the example below, the program tries to divide by zero and handles the error with the except block:

python
try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero")  # Output: Cannot divide by zero

14. False

The False keyword is a Boolean value in Python that represents the logical value of false.

It is used in conditional statements to check for a "false" condition or represent something that is not true.

Common uses:

  • Representing a false condition in logical expressions.
  • Returning a logical false value from functions.

In the example below, the program checks if a variable is equal to False:

python
x = False

if x == False:
    print("x is False")  # Output: x is False

15. finally

The finally keyword is used in a try-except block to define code that will always run, regardless of whether an exception occurred or not.

This is useful when you need to ensure that certain actions (like closing files or releasing resources) are performed no matter what happens in the try or except blocks.

Common uses:

  • Executing cleanup code, like closing files.
  • Ensuring that specific actions are always taken after code execution.

In the example below, the program executes the finally block even if there is an exception in the try block:

python
try:
    x = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero")
finally:
    print("This will always run")  # Output: This will always run

16. for

The for keyword is used to iterate over a sequence (like a list, tuple, or string) and perform an action for each item in that sequence.

This is useful when you need to repeat an action multiple times for each element in a collection of items.

Common uses:

  • Looping through lists, strings, and other iterable objects.
  • Repeating an action for each item in a collection.

In the example below, the program loops through a list of numbers and prints each one:

python
numbers = [1, 2, 3, 4]

for number in numbers:
    print(number)  # Output: 1, 2, 3, 4

17. from

The from keyword is used in imports to bring specific parts of a module into your current program.

This is useful when you only want to use certain functions or classes from a module, rather than importing everything.

Common uses:

  • Importing specific functions, classes, or variables from a module.
  • Making the code cleaner by avoiding unnecessary imports.

In the example below, we import the sqrt function from the math module and use it to calculate the square root:

python
from math import sqrt

result = sqrt(16)
print(result)  # Output: 4.0

18. global

The global keyword is used to declare a variable as global, meaning it can be accessed and modified from anywhere in your code.

This is useful when you need to modify a variable that is defined outside a function or when you need to share the variable's value across multiple functions.

Common uses:

  • Making a variable global so it can be accessed by different functions.
  • Modifying a global variable within a function.

In the example below, the global keyword is used to modify the global variable x within a function:

python
x = 10

def modify_x():
    global x
    x = 20

modify_x()
print(x)  # Output: 20

19. if

The if keyword is used to evaluate a condition and run a block of code only if the condition is true.

This is useful when you want your program to make decisions based on certain conditions and take different actions depending on the outcome.

Common uses:

  • Checking if a condition is true before running certain code.
  • Making decisions in your program based on input or data.

In the example below, the program checks if a number is greater than 10:

python
x = 15

if x > 10:
    print("x is greater than 10")  # Output: x is greater than 10

20. import

The import keyword is used to bring modules or libraries into your Python program, so you can use their functions and classes.

This is useful when you need to use code that is already written in a module (like the math module for mathematical functions) rather than writing everything from scratch.

Common uses:

  • Importing entire modules for use in your code.
  • Accessing functions, classes, and variables from external libraries.

In the example below, the math module is imported and its sqrt function is used to calculate the square root of a number:

python
import math

result = math.sqrt(16)
print(result)  # Output: 4.0

21. in

The in keyword is used to check if a value exists in a sequence (like a list, string, or tuple) or to iterate over items in a collection.

This is useful for checking membership (whether a value is in a list or other collection) or looping through each item in a sequence.

Common uses:

  • Checking if an item exists in a collection.
  • Looping through items in a sequence using a for loop.

In the example below, we check if a number exists in a list:

python
numbers = [1, 2, 3, 4]

if 3 in numbers:
    print("3 is in the list")  # Output: 3 is in the list

22. is

The is keyword is used to test object identity, meaning it checks if two variables point to the same object in memory.

This is different from the equality operator ==, which checks if the values of two variables are equal. is checks if two variables are the same object.

Common uses:

  • Testing if two variables refer to the same object in memory.
  • Used for comparing None in Python.

In the example below, we check if two variables refer to the same object:

python
a = [1, 2, 3]
b = a

if a is b:
    print("a and b refer to the same object")  # Output: a and b refer to the same object

23. lambda

The lambda keyword is used to create small, anonymous functions. These are sometimes called lambda functions.

Lambda functions are useful when you need a quick function for a short period and don't want to define a full function using def.

Common uses:

  • Creating simple one-liner functions.
  • Used in functional programming tools like map, filter, and sorted.

In the example below, a lambda function is used to square a number:

python
square = lambda x: x * x
print(square(5))  # Output: 25

24. nonlocal

The nonlocal keyword is used to declare a variable in a nested function, making it refer to a variable in the nearest enclosing scope that is not global.

This is useful when you need to modify a variable in a nested function but you don't want to make it a global variable.

Common uses:

  • Modifying variables from outer but non-global scopes.
  • Accessing and modifying variables in closures.

In the example below, the nonlocal keyword is used to modify a variable in a nested function:

python
def outer_function():
    x = 10
    def inner_function():
        nonlocal x
        x += 5
    inner_function()
    return x

print(outer_function())  # Output: 15

25. not

The not keyword is used to reverse the Boolean value of an expression. It turns True to False and vice versa.

This is useful when you need to check the negation of a condition.

Common uses:

  • Reversing a condition's result.
  • Using in if statements to execute code if a condition is False.

In the example below, not is used to check if a condition is False:

python
x = 5

if not x > 10:
    print("x is not greater than 10")  # Output: x is not greater than 10

26. None

The None keyword is used to represent the absence of a value or a null value. It is the only value of the NoneType data type.

You can use None to indicate that a variable or function does not have any value assigned or to represent a missing or undefined value.

Common uses:

  • Returning no value from a function.
  • Initializing variables to indicate no value.

In the example below, we check if a variable is None:

python
x = None

if x is None:
    print("x has no value")  # Output: x has no value

27. or

The or keyword is used to combine two conditions, where if either of the conditions is true, the entire expression evaluates as true.

This is useful when you want to check if at least one condition is true, and if so, execute some code.

Common uses:

  • Checking if at least one condition is true.
  • Using in if statements to make multiple conditions more flexible.

In the example below, the program checks if either condition is true:

python
x = 5
y = 10

if x > 0 or y < 0:
    print("At least one condition is true")  # Output: At least one condition is true

28. pass

The pass keyword is used as a placeholder when you need to have a statement, but you don't want to do anything. It’s often used in empty functions or classes, or as a temporary placeholder during development.

It does nothing when executed, but it allows you to write syntactically correct code without errors.

Common uses:

  • Creating empty functions or classes.
  • To temporarily skip a part of code during development.

In the example below, we use pass to create an empty function:

python
def placeholder_function():
    pass  # No action is taken

29. raise

The raise keyword is used to throw an exception, either a predefined one or a custom exception.

It is typically used in error handling to stop the normal flow of code and signal that something went wrong.

Common uses:

  • Throwing an exception to handle errors.
  • Creating custom exceptions with error messages.

In the example below, we use raise to trigger an exception:

python
def check_age(age):
    if age < 18:
        raise ValueError("Age must be 18 or older")

check_age(15)  # Output: ValueError: Age must be 18 or older

30. return

The return keyword is used to exit a function and optionally pass a value back to the caller.

It is essential for any function that needs to give a result after performing some task.

Common uses:

  • Returning a value from a function.
  • Exiting a function early.

In the example below, we use return to get the result of a function:

python
def add_numbers(a, b):
    return a + b

result = add_numbers(5, 3)
print(result)  # Output: 8

31. True

The True keyword is a Boolean value representing the logical value of true.

It is commonly used in conditional expressions, where you want to check if something is true.

Common uses:

  • In if statements to check if a condition is true.
  • In loops to control the flow when conditions are true.

In the example below, we check if a condition is True:

python
x = True

if x:
    print("x is True")  # Output: x is True

32. try

The try keyword is used to start a block of code that might cause an error. If an error occurs, Python will move to the except block.

It's often used for error handling to ensure your program doesn’t crash when encountering issues.

Common uses:

  • Wrap code that might raise an exception.
  • Handle errors gracefully with except.

In the example below, the program tries to divide by zero, but an exception is handled:

python
try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero")  # Output: Cannot divide by zero

33. while

The while keyword is used to start a loop that will continue to execute as long as a specified condition is true.

It is often used when you don't know in advance how many times you need to loop, but want to keep repeating until a condition is met.

Common uses:

  • Repeating a task until a condition becomes false.
  • Creating an infinite loop (use cautiously).

In the example below, the loop continues until x becomes greater than 5:

python
x = 1

while x <= 5:
    print(x)  # Output: 1, 2, 3, 4, 5
    x += 1

34. with

The with keyword is used to simplify resource management, such as opening files. It automatically takes care of setup and cleanup tasks, ensuring that resources are properly managed.

It's typically used with files, network connections, or other resources that need to be closed after use.

Common uses:

  • Managing resources like files, ensuring they are automatically closed after use.
  • Handling setup and teardown for complex tasks like database connections.

In the example below, with ensures that the file is automatically closed after reading:

python
with open('file.txt', 'r') as file:
    content = file.read()
    print(content)  # Automatically closes the file after use

35. yield

The yield keyword is used in a function to make it a generator. Instead of returning a single value, the function will return an iterator that produces a sequence of values, one at a time.

It is useful for creating iterators that need to return a series of values lazily (on-demand) without storing them all in memory.

Common uses:

  • Creating generator functions.
  • Returning values one at a time from a function, rather than all at once.

In the example below, we use yield to create a generator that produces numbers one by one:

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

for number in count_up_to(3):
    print(number)  # Output: 1, 2, 3

What's Next?

Up next, you'll explore Python errors and exceptions. You'll learn how to identify common runtime issues, use try-except blocks, and write more robust, error-resistant code.