Python Tutorial

Python Keywords List (All Keywords in Python With Examples)

Table of Contents

  • Introduction
  • List of Python Keywords
  • Value Keywords in Python: True, False, None
  • Python Operator Keywords: and, or, not, in, is
  • Python Iteration Keywords: for, while, break, continue
  • Python Conditional Keywords: if, else, elif
  • Python Structure Keywords: def, class, with, as, pass, lambda
  • Python Returning Keywords- return, yield
  • Python Import Keywords- import, from
  • Python Exceptional Handling Keywords: try, except, raise, finally, assert
  • Python Variable Handling Keywords: del, global, nonlocal
  • Python Asynchronous Keywords- async, await
  • How to Identify Python Keywords?
  • How to Retrieve All Keywords in Python?
  • MCQs Related to Python Keywords

Introduction

Every programming language has a set of reserved words called keywords with specific meanings and restrictions around how they must be used. Python keywords are the basic building blocks of Python programs. In this article, we have introduced all Python keywords to help you learn more about each keyword.

List of Python Keywords

Python keywords are unique reserved words with specific meanings and purposes and can't be used for anything but those particular purposes. 

These keywords are always available; you don't have to import them into your code. Python keywords are different from Python's built-in functions and types. 

The total number of keywords in Python is 35, as listed below:

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

 

Value Keywords in Python: True, False, None

Let’s first understand the value keywords:

  • True

Keyword True represents a boolean true; True is printed if a statement is correct.

  • False

Keyword False represents a boolean false; if a statement is wrong, False is printed. 

Example of True and False Keywords:

# Boolean values
is_raining = True
has_sunshine = False
if is_raining:
    print("Remember to take an umbrella.")
if not has_sunshine:
    print("It's a cloudy day.")
  • None

Keyword None is a particular constant that denotes a null value or a void. Remember 0, any empty container, for e.g. an empty list doesn't compute to None and is an object of its NoneType datatype. You cannot create multiple None objects and assign them to variables.

Example of None keyword:

# Using None to initialize a variable without a value
name = None
if name is None:
    print("Name has not been provided.")
# Function with no return value
def greet(name):
    print("Hello, " + name)
result = greet("Alice")
print("Result:", result)

Python Operator Keywords: and, or, not, in, is

Various keywords in Python are used as operators for performing mathematical operations. In computer languages, these operators are represented as &, |, and !. 

All of these are keyword operations in Python:

Mathematical Operations

Other Language Operators

Python Keyword

AND, ∧

&&

and

OR, ∨

ll

or

NOT, ¬

!

not

CONTAINS, ∈

 

in

IDENTITY

===

is

 

Python code was designed for readability; therefore, many operators that use symbols in other programming languages are keywords in Python.

  • and

The Python keyword and checks if both the left-hand side and right-hand side operands are true or false. The result will be True if both components are true, and if one is false, the result will also be False.

A

A and B

True

True

True

False

True

False

True

False

False

False

False

False

 

Note that the result of an and statement isn't always True or False due to and's strange behaviour; this is the case. Instead of processing the inputs to corresponding Boolean values, it gives if false or if true. 

The outputs of a and term could be utilised with a conditional if clause or provided to bool() to acquire an obvious True or False answer.

Example:

age = 25
has_license = True
if age >= 18 and has_license:
    print("You can drive a car.")
else:
    print("You are not eligible to drive.")

Output:

You can drive a car.

 

  • or

This logical operator in Python checks if, at minimum, 1 of the inputs is true. If the first argument is true, the or operation yields it; otherwise, the second argument is returned.

A

A or B

True

True

True

False

True

True

True

False

True

False

False

False

 

The or keyword doesn’t change its inputs to corresponding Boolean values; instead, the results are determined on the basis of if they are true or false.

Example:

is_weekend = False
is_holiday = True
if is_weekend or is_holiday:
    print("It's a good time for a picnic!")
else:
    print("Work and responsibilities await.")

Output:

It's a good time for a picnic!

 

  • not

Python’s not keyword gets the opposite Boolean value of a variable. The not keyword in conditional statements or other Boolean expressions inverts the Boolean meaning or result. The not determines the explicit Boolean value, True or False, and returns the opposite.

A

not A

True

False

False

True

Example:

is_raining = True
if not is_raining:
    print("Enjoy the sunny day!")
else:
    print("Don't forget your umbrella.")

Output:

Don't forget your umbrella.

 

  • in

The in keyword checks if a container contains a value. It is also used to loop through the container.

Example:

fruits = ["apple", "banana", "orange"]
if "banana" in fruits:
    print("Banana is in the list of fruits.")
else:
    print("Banana is missing from the list.")

Output:

Banana is in the list of fruits.

 

  • is

The is keyword tests object identity, i.e., it checks whether both objects take the same memory location or not. 

Example:

x = [1, 2, 3]
y = x
if x is y:
    print("x and y reference the same object.")
else:
    print("x and y reference different objects.")

Output:

x and y reference the same object.

Python Iteration Keywords: for, while, break, continue

Python provides several iteration keywords and constructs that allow you to repeat a block of code multiple times or iterate over sequences. 

Here are the main iteration-related keywords in Python:

  • for: 

The for keyword controls flow and for a loop.

Example:

numbers = [1, 2, 3, 4, 5]
for num in numbers:
    print(num)

Output:

1

2

3

4

5

 

  • while: 

Has a similar working like for, used to control flow and for a loop.

Example:

count = 0
while count < 5:
    print("Count:", count)
    count += 1

Output:

Count: 0
Count: 1
Count: 2
Count: 3
Count: 4

 

  • break: 

break keyword controls the loop flow. The statement is used to break the loop and pass the control to the statement following immediately after the loop.

Example:

numbers = [1, 2, 3, 4, 5]
for num in numbers:
    if num == 3:
        print("Found 3, stopping loop.")
        break
    print(num)

Output:

1
2
Found 3, stopping loop.

 

  • continue: 

continue keyword is also used to control the code flow. This keyword skips the current loop's iteration but doesn't end the loop.

Example:

numbers = [1, 2, 3, 4, 5]
for num in numbers:
    if num == 3:
        print("Skipping 3.")
        continue
    print(num)

Output:

1
2
Skipping 3.
4
5

Example- for, while, break keywords

# Using a for loop to print even numbers and a while loop to find the first multiple of 7
# For loop to print even numbers
print("Even numbers:")
for num in range(1, 11):
    if num % 2 == 0:
        print(num)
# While loop to find the first multiple of 7
print("\nFinding the first multiple of 7:")
count = 1
while True:
    if count % 7 == 0:
        print("The first multiple of 7 is:", count)
        break  # Exit the while loop
    count += 1
# Using continue in a loop
print("\nSkipping 'apple' and 'banana' from the fruits list:")
fruits = ["apple", "banana", "orange", "grape", "kiwi"]
for fruit in fruits:
    if fruit == "apple" or fruit == "banana":
        print("Skipping", fruit)
        continue  # Skip the rest of the loop body and move to the next iteration
    print("Fruit:", fruit)

Output:

Even numbers:
2
4
6
8
10
Finding the first multiple of 7:
The first multiple of 7 is: 7
Skipping 'apple' and 'banana' from the fruits list:
Skipping apple
Skipping banana
Fruit: orange
Fruit: grape
Fruit: kiwi

Python Conditional Keywords: if, else, elif

Python provides conditional keywords that allow you to control the flow of your programs based on different conditions. 

Here are the main conditional keywords in Python:

  • if

if is a control statement for decision-making. Truth expression forces control to go in if statement block.

  • else 

It is a control statement for decision-making. False expression forces control to go in else statement block.

  • elif

It is short for else if and is a control statement for decision-making. 

Example of if, else, elif keywords in Python

# Program to classify a student's grade based on their exam score
score = 85
if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
elif score >= 60:
    grade = "D"
else:
    grade = "F"
print("Student's grade:", grade)

Output:

Student's grade: B

Python Structure Keywords: def, class, with, as, pass, lambda

You must use one of the Python keywords in this section to define functions and classes or use context managers. They are an important part of the Python language, and understanding when to use them helps you become a better Python programmer.

  • def 

The def Python keyword is used to declare user-defined functions. 

  • class 

The class keyword is used to declare user-defined classes. 

  • with

The with keyword wraps the execution of a code block within methods defined by the context manager. This keyword is used sparingly in day-to-day programming. 

  • as

The as keyword creates the alias for the module imported. i.e. gives a new name to the imported module. 

  • pass

The pass keyword is the null statement in Python. Nothing happens when this keyword is used. This prevents indentation errors and is used as a placeholder. 

This keyword makes inline returning functions with no statements allowed internally. 

Example of Structure Keywords in Python:

# Defining a function, creating a class, using 'with' for file handling, and creating a lambda function
# Defining a function
def greet(name):
    return f"Hello, {name}!"
# Creating a class
class Rectangle:
    def __init__(self, width, height):
        self.width = width
        self.height = height
    def area(self):
        return self.width * self.height
# Using 'with' for file handling
file_path = "example.txt"
with open(file_path, "w") as file:
    file.write("Hello, this is an example file.")
# Using 'as' to give a shorter alias
import math as m
radius = 5
area = m.pi * m.pow(radius, 2)
print("Area of circle:", area)
# Using 'pass' as a placeholder
def some_function():
    pass  # Placeholder, no action required
# Creating a lambda function
multiply = lambda x, y: x * y
# Calling the defined function and class, and using the lambda function
name = "Alice"
greeting = greet(name)
print(greeting)
rectangle = Rectangle(4, 6)
print("Rectangle area:", rectangle.area())
result = multiply(3, 5)
print("Result of multiplication:", result)

Output:

Area of circle: 78.53981633974483
Hello, Alice!
Rectangle area: 24
Result of multiplication: 15

Python Returning Keywords- return, yield

Here are the main returning keywords and constructs in Python:

  • return

The return keyword is used to specify the value that a function should return when it's called. It ends the execution of the function and sends a value back to the caller.

Example:

def add(a, b):
    return a + b
result = add(3, 5)
print("Result:", result)

Output:

Result: 8

 

  • yield

The yield keyword is used in generator functions to produce a series of values, allowing the function to maintain its state between calls.

Example:

def generate_numbers():
    for i in range(5):
        yield i
num_generator = generate_numbers()
for num in num_generator:
    print(num)

Output:

0
1
2
3
4

Python Import Keywords- import, from

Here are the main import keywords and constructs in Python:

  • import

The import keyword is used to bring external modules or libraries into your Python program, allowing you to use functions, classes, and variables defined in those modules.

Example:

import math
result = math.sqrt(25)
print("Square root of 25:", result)

Output:

Square root of 25: 5.0

 

  • from

The from keyword is used with import to selectively import specific items (functions, classes, etc.) from a module.

Example:

from math import sqrt
result = sqrt(36)
print("Square root of 36:", result)

Output:

Square root of 36: 6.0

Python Exceptional Handling Keywords: try, except, raise, finally, assert

Following are the main keywords and constructs used for exception handling in Python:

  • try

The try keyword is used to start a block of code where exceptions might occur.

Example:

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Error: Division by zero")

Output:

ERROR!
Error: Division by zero

 

  • except

The except keyword is used to specify the block of code that should be executed if a specific exception occurs.

Example:

try:
    value = int("abc")
except ValueError:
    print("Error: Invalid conversion to int")

Output:

ERROR!
Error: Invalid conversion to int

 

  • finally

The finally keyword is used to specify a block of code that is always executed, regardless of whether an exception occurred.

Example:

try:
    file = open("example.txt", "r")
    content = file.read()
except FileNotFoundError:
    print("File not found")
finally:
    file.close()

Output:

File not found

 

  • raise

The raise keyword is used to explicitly raise exceptions or errors at a specific point in your code.

Example:

def divide(a, b):
    if b == 0:
        raise ValueError("Division by zero is not allowed.")
    return a / b
try:
    result = divide(10, 0)
except ValueError as e:
    print("Error:", e)

Output:

ERROR!
Error: Division by zero is not allowed.

 

  • assert

The assert keyword is used to check conditions that should be true. If the condition is false, an AssertionError is raised.

Example:

def positive_number(num):
    assert num > 0, "Number must be positive"
    return num
try:
    result = positive_number(-5)
except AssertionError as e:
    print("Error:", e)

Output:

ERROR!
Error: Number must be positive

Python Variable Handling Keywords: del, global, nonlocal

Below are the keywords used for variable handling in Python:

  • del

The del keyword is used to delete a variable or an item from a data structure (like a list or dictionary).

my_var = 5
del my_var

 

  • global

The global keyword is used to indicate that a variable inside a function should refer to a global variable, rather than creating a new local variable.

Example:

count = 0
def increment():
    global count
    count += 1
increment()
print("Count:", count)

Output:

Count: 1

 

  • nonlocal 

The nonlocal keyword is used to indicate that a variable inside a nested function should refer to a variable in an outer (enclosing) function's scope.

Example:

def outer_function():
    x = 10
    def inner_function():
        nonlocal x
        x += 5
        print("Inner:", x)
    inner_function()
    print("Outer:", x)
outer_function()

Output:

Inner: 15
Outer: 15

Python Asynchronous Keywords- async, await

  • async and await 

The async keyword is used to define asynchronous functions, and the await keyword is used inside async functions to pause execution and await the completion of another asynchronous operation.

Example:

import asyncio
async def foo():
    print("Foo start")
    await asyncio.sleep(2)
    print("Foo end")
async def main():
    await asyncio.gather(foo(), foo())
asyncio.run(main())

Output:

Foo start
Foo start
Foo end
Foo end

How to Identify Python Keywords?

Python keyword list has changed over a period of time. The await and async keywords were added in Python 3.7. The print and exec were keywords present in Python 2.7 but are now turned into built-in functions in Python 3+. 

In the below sections, you will learn how to find out which words are keywords in Python.

  • Use an IDE Code with Syntax Highlighting 

There are several Python Compilers and IDEs available. They all highlight keywords setting them apart from the rest of the terms in the code. This facility assists in immediately identifying Python keywords during coding so that you do not misuse them.

  • Verify Keywords with Code in a REPL

In the Python REPL, there are several ways through which you can identify valid Python keywords and learn more about them.

  • Check for Syntax Error

Lastly, another way to check that a word you use is a keyword is if you get a syntax error while trying to assign to it, name a function with it, or do something else that isn’t allowed. This technique is a bit harder, but in this way, Python will let you know you are misusing a keyword.

How to Retrieve All Keywords in Python?

We can retrieve all Python keywords names using the following code:

# Program to view Python keyword list
import keyword
def main():
    keywords = keyword.kwlist
    print("Keywords in Python:")
    for kw in keywords:
        print(kw)
if __name__ == "__main__":
    main()

Output:

Keywords in Python:
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

MCQs Related to Python Keywords

Here are some multiple-choice questions (MCQs) related to keywords in Python:

1. Which of the following statements about keywords in Python is true?

   a) Keywords are case-sensitive.

   b) Keywords can be used as variable names.

   c) New keywords can be added to Python.

   d) Keywords are used for user-defined functions.

Answer: a)

2. How many keywords are there in Python?

   a) 15

   b) 25

   c) 35

   d) 45

Answer: c) 

3. What happens if you try to use a keyword as a variable name in Python?

   a) It works fine and does not cause any issues.

   b) It raises a syntax error.

   c) It automatically converts the variable name to a string.

   d) It prompts a warning but allows the usage.

Answer: b)

4. Which keyword is used to define a block of code in Python?

   a) if

   b) for

   c) def

   d) pass

Answer: c) 

5. Which keyword is used to handle exceptions in Python?

   a) try

   b) except

   c) raise

   d) finally

Answer: a) 

6. Can you add or modify keywords in Python?

   a) Yes, keywords can be added or modified.

   b) No, keywords are fixed and cannot be added or modified.

Answer: b) 

7. Which keyword is used to exit a loop prematurely in Python?

   a) break

   b) continue

   c) exit

   d) stop

Answer: a) 

8. Which keyword is used to specify the end of a loop iteration and start the next iteration in Python?

   a) break

   b) continue

   c) skip

   d) next

Answer: b) 

9. Which keyword is used to check a condition and raise an exception if it is False?

   a) assert

   b) check

   c) validate

   d) ensure

Answer: a) 

10. Which keyword is used to define a class in Python?

    a) class

    b) def

    c) struct

    d) object

Answer: a) 

11. All keywords in Python are in?

    a) uppercase

    b) lowercase

    c) title case

    d) sentence case

Answer: b)

12. Which of the following words are reserved words in Python?

a) function

b) import

c) string

d) variable

Answer: b)

Python Keywords FAQs

Keywords in Python are reserved words that have predefined meanings and functionalities in the language. They are used to define the structure, behavior, and flow of a Python program. Keywords cannot be used as identifiers (variable names, function names, etc.).
There are 35 keywords in Python. These keywords serve various purposes, such as defining control structures, data types, and program logic.
No, you cannot use keywords as variable names or identifiers. Python will raise a syntax error if you attempt to use a keyword as an identifier.
The pass keyword is a placeholder that does nothing. It is often used as a temporary stub when you need syntactically correct code but haven't yet implemented the actual logic.
None is a special constant in Python that represents the absence of a value or a null value. It is often used as a default return value for functions that don't explicitly return anything.
Iteration keywords in Python include for and while, which are used to create loops. Loops allow you to repeatedly execute a block of code, either for a fixed number of times (for loop) or as long as a certain condition is met (while loop).
Did you find this article helpful?