All Python Keywords: At One Place


In this article, we will discuss all the Python keywords and their usage in detail. We will cover each keyword with a description and examples.

Python Keywords

Keywords in Python are some special reserved words that have special meanings and serves a special purpose in programming. They are used to define the functionality, structure, data, control flow, logic, etc in Python programs.

Keywords can't be used for another purpose other than what they are reserved for. You can't use a keyword as a variable name, function name, etc.

Python keyword are case sensitive and are globally available. You can use them in any Python program without importing any module.

Python keywords are also known as Python reserved words.

Every programming language has its own set of keywords. Python has 33 keywords in total as of Python 3.7. The following table lists all the Python keywords.

False None True and as
assert 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

Note: async and await are also keywords used for asynchronous programming but to use them, you need to import asyncio module so they are excluded from the list of keywords in this article.

The above table lists all the Python keywords. We will discuss each keyword by grouping them with their common usage. But before that let's see how can we get a list of all Python keywords.

Get list of Python keywords

To get a list of all Python keywords first import the keyword module and use the keyword.kwlist function to get the list of all Python keywords.

# Get list of all Python keywords
import keyword
print(keyword.kwlist)

#checking length
print(f"Total number of keywords: {len(keyword.kwlist)}")

The above code will print the list of all Python keywords.

Output:

['False', 'None', 'True', 'and', 'as', 'assert', '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']
Total number of keywords: 33

You can also check for an individual keyword if it is a keyword or not by using keyword.iskeyword function. It will return True if the given string is a Python keyword.

# Check for individual keyword
import keyword

# True
print(keyword.iskeyword("import"))
# False
print(keyword.iskeyword("async"))

Output:

True
False


Python Keywords Usage

Let's now categorize all the Python keywords with their usage and look at their usage in detail with examples.

Boolean Keywords

Boolean keywords are used to define truthy and falsy values in the programs. Truthy are the values which are evaluated to True and falsy are those that are evaluated to False.

Keyword Description
True True is a keyword used to define true value in Python
False False is a keyword used to define false value in Python

1. True keyword

The True in python is used to define true values. If a given condition is true then python returns True.

To check truthy value of a variable in Python, use the bool() function. Almost all the values in Python are truthy except False, 0, [], (), {}, None, '', etc.

Unlike other programming languages, Python uses True, not true to define truthy values.

Here is truth table for True keyword:

A B A and B A or B A not B
True True True True False
True False True True False
False True True True False
False False False False True

For example:

# Code to check 'True' keyword
if True:
    print("True")

print(bool(10)) # True
print(bool(0)) # False
print(bool([])) # False

Output:

True
True
False
False

2. False keyword

The False in python is used to define false values. If a given condition is false then python returns False.

Python uses False, not false to define falsy values.

For example:

# Code to check 'False' keyword
if False:
    print("False")

Output:

False

3. None keyword

The None keyword is used to define the null value in Python. (null means no value)

None value doesn't define 0 or '' (empty string), it just means nothing is there.

None is also the default return value of a function in python. This means if a function doesn't return any value then it returns None.

Example:

# default return of a function is None
def message():
    greet = "Hello"

print(message())  # None

Output:

None

Operator Keywords

Operator keywords are used as operators in Python. They are used to perform mathematical operations, logical operations, comparison operations, etc.

Here is list of Operator keywords in Python:

Keyword in other language Description
and && and in python is used to check if both the conditions are true
or || or in python is used to check if either of the conditions are true
not ! not is used to reverse truth value of a condition
is === is is used to check if two variables are equal
in in checks if a value is present in a list or dictionary

4. and keyword

The and keyword in python determines the truth value of the operands. If both of the operands are truthy then it returns a truthy value, else returns falsy.

If you compare 2 values and the first has a truthy value then the second value is returned and if the first value is falsy then the first value is returned.

Note: Other programming languages return 0 for falsy value and 1 for truthy value but python returns an actual value.

Example

# Code to check 'and' keyword
a = 10 and 20
print(a)
# 20, because 10 is truthy

b = 0 and 20
print(b)
# 0, because 0 is falsy

c = 10 and 15 and 20
print(c)
# 20, think why

Output:

20
0

5. or keyword

The or keyword in python determines the truth value of the operands. If any of the operands is truthy then it returns a truthy value, else returns falsy.

If you compare 2 values and the first has a truthy value then the first value is returned and if the first value is falsy then the second value is returned.

Example

# Code to check 'or' keyword
a = 10 or 0
print(a)
# 10, because 10 is truthy

b = 0 or 20
print(b)
# 20, because 0 is falsy

c = 0 or False
print(c)
# False, because 0 is falsy

Output:

10
20
False

6. not keyword

The not keyword reverses the truth value of the operand. If the operand is truthy then it returns a falsy value and if the operand is falsy then it returns a truthy value.

The value of the operand is converted to a boolean value and then reverse value.

Example

# Code to check 'not' keyword
a = not 10
print(a)
# False, because 10 is truthy

print(not 0) # True
print(not False) # True
print(not True) # False

Output:

False
True
False

7. is keyword

The is keyword is used to check if two variables are equal or not. It returns True if both the variables are the same else returns False.

Example

# Code to check 'is' keyword
a = 10
b = 10
c = "10"
print(a is b)  # True
print(a is c)  # False
print(a is not c)  # True

Output:

True
False
True

8. in keyword

The in keyword is used to check if a value is present in a list or dictionary. It returns True if the value is present in the list or dictionary, else returns False.

You can use in keyword to check if a character is present in a string or not, a value is present in a list or dictionary or not, etc.

Example

# Code to check 'in' keyword
a = 10
b = [10, 20, 30]
c = "10"
print(a in b)  # True
print(c in b)  # False

name = "John"
print("J" in name)  # True
print("b" in name)  # False

Output:

True
False
True
False

Conditional keywords

Conditional keywords are used to create conditional statements in python. They are used to check the condition and execute the block of code on the basis of the truth value of the condition.

Python has 3 conditional keywords:

Keyword Description
if The if keyword is used to start a conditional statement. It checks a given condition and executes a block of code if the condition is true
elif The elif keyword is used to check another condition if the first condition is false. If the condition used in elif is true, then the block of code corresponding to it will be executed
else The else keyword is used to execute a block of code if all the above conditions are false

9. if keyword

The if keyword is one of the most useful conditional keywords in python. It executes a block of code conditionally.

Here is a simple example of if keyword

# Ccode using if keyword
a = 10
if a > 5:
    print("a is greater than 5")

Output:

a is greater than 5

10. elif keyword

The elif keyword is also part of conditional statements. It is used when you have more than one condition to check. If the first condition is false, then it will provide another condition to check.

Example

# Code using elif keyword
a = 5
if a > 5:
    print("a is greater than 5")
elif a == 5:
    print("a is equal to 5")
else:
    print("a is less than 5")

Output:

a is equal to 5

11. else keyword

The else keyword is used in conditional statements when none of the conditions is true.

It is the final block of code that will definitely be executed if all the conditions are false.

Example

# Code using else keyword
num = 100
if num < 1:
    print("Number is less than 1")
elif num < 10:
    print("Number is less than 10")
else:
    print("Number is greater than or equal to 100")

Output:

Number is greater than or equal to 100

Iteration keywords

Iteration or looping is one of the most useful concepts in a programming language. As a programmer, you are going to use iteration almost every time.

Iteration is the process of repeating a block of code until a condition is met. It is used to execute a block of code a given number of times.

Pythons have few keywords to be used for iteration:

Keyword Description
for The for keyword is used to iterate over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).
while The while keyword also used to create a loop, but it performs iterations until a condition is false.
break The break keyword is used to terminate the loop.
continue The continue keyword is used to skip the current iteration and continue with the next iteration.

12. for keyword

The for keyword is used to create for loop in python, which is the most used loop in python programming.

A loop is used to execute a set of statements multiple times. Suppose you want to print the numbers from 1 to 100. Then you are not going to print for individual number, but just start a loop and it will do the same.

Here is a simple example of a loop using for keyword

# Code using for keyword
# Prints numbers from 1 to 10
for i in range(1,11):
    print(i, end=" ")
# end=" " causing not to create new line bt space saperated output

Output:

1 2 3 4 5 6 7 8 9 10

There is another loop that uses the for keyword is for-each loop. It iterates over a collection of items and executes a block of code for each item.

# Example of for-each loop
arr = [1, 2, 3, 4, 5]
for i in arr:
    print(i, end=" ")

Output:

1 2 3 4 5

13. while keyword

The while keyword is used to create a while loop in python. While loop is used when you don't know the number of iteration you need to perform but you know the condition that will be true for a given number of times.

For each iteration of the while loop, you check for a condition if the condition is true then execute the block of code otherwise terminate the loop.

# Code using while keyword
# sum of natural numbers until sum is 1000
sum = 0
i = 1
while sum < 1000:
    sum = sum + i
    i = i + 1
print(f"We added the first {i-1} numbers and the sum is {sum}")

Output:

We added the first 45 numbers and the sum is 1035

14. break keyword

The break keyword has a very significant role in loops. It is used to terminate the loop when a condition is met.

Think of an example where you want to add the first 100 numbers but want to stop the loop when the sum is greater than 1000. In this case, you can use break keyword to stop the loop by creating a condition.

# Code using break keyword
# sum of natural numbers until sum is 1000
sum = 0
i = 1
for i in range(1,101):
    sum = sum + i
    if sum > 1000:
        break
print(f"We break after adding the first {i} numbers and the sum is {sum}")

Output:

We break after adding the first 45 numbers and the sum is 1035

15. continue keyword

The continue keyword is used to skip the current iteration and continue with the next iteration.

Suppose you want to print the sum of first 10 numbers but not 5 and 7. In this case, you can use continue keyword to skip the current iteration for these numbers.

# Code using continue keyword
# sum of natural numbers until sum is 1000
sum = 0
i = 1
for i in range(1,11):
    if i == 5 or i == 7:
        continue
    sum = sum + i
print(f"We skip 5 and 7 and the sum is {sum}")

Output:

We skip 5 and 7 and the sum is 43

Import keyword

Python has many features which you can not use directly in your code. You will have to first import them into your code.

Things that are generally used in programming are readily available in python. But there are 1000s of features for which you have to import some modules in your code. Example pandas, NumPy, matplotlib, etc.

There are 3 keywords used for import purposes in python.

Keyword Description
import The import keyword is used to import a module in python.
from The from keyword is used to import specific features from a module.
as The as keyword is used to rename the imported feature.

16. import keyword

The import keyword is used to import a module in python which is not readily available.

Once you import a module in your code then you can use the features of that module in your code.

# Code using import keyword
import math
print(math.sqrt(25))

Output:

5.0

17. from keyword

The from keyword instead of importing a whole module, it only imports specific features from a module.

Once you import a specific feature you can directly use it without referring to the module name.

# Code using from keyword
from math import sqrt
print(sqrt(25))

Output:

5.0

18. as keyword

The as keyword is used to rename the imported feature.

Renaming of modules is so frequent in python that there are some community standard names for modules. example pandas as pd, numpy as np, matplotlib as plt, etc.

# Code using as keyword
from math import sqrt as square_root
print(square_root(25))

Output:

5.0

Function and structure keywords

Pythons have few keywords that are used to create a structure in your code. It can be a function, a class, etc.

These are very useful parts of python for writing a rich set of code.

Here is a table showing structure keywords in python.

Keyword Description
def The def keyword is used to create a function in python.
class The class keyword is used to create a class in python.
with The with keyword is used to create a context manager
pass The pass keyword is used to create a pass statement in python.
lambda The lambda keyword is used to create a lambda function in python.

19. def keyword

Function is a block of code which is used to perform a specific task. It is also known as a subroutine.

In python, a function is defined using the def keyword.

The def keyword is followed by the name of the function and then the parentheses ().

The code inside the parentheses is the block of code that is executed when the function is called.

The code inside the parentheses can have any number of arguments and can have any number of statements.

# Code using def keyword
def add(a, b):
    sum = a + b
    print(sum)

# calling the function
add(10, 20)

Output:

30

20. class keyword

Class is a block of code that behaves like a blueprint for creating objects.

A class is defined using the class keyword followed by the name of the class.

You can define multiple properties and methods inside a class and when you create an object of that class then all the properties and methods are copied to the object.

# using class keyword
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def display(self):
        print(f"{self.name} is {self.age} year old")

# creating an object
p = Person("John", 30)
p.display()

Output:

John is 30 year old

21. with keyword

The with keyword is used to create a context manager. It is used to create a context in which a block of code can be executed.

It makes code more readable and less error prone.

# using with keyword
with open("test.txt", "w") as file:
    file.write("Hello World")

The above code will create a file called test.txt in the current directory and write the string "Hello World" inside it, while using the with keyword you need not explicitly close the file.


22. pass keyword

The pass keyword is used to tell python that the statement is intentionally left blank. It is used when a statement is required syntactically but the program requires no action. like a label in C.

# using pass keyword
def message:
    pass

class Person:
    pass

23. lambda keyword

The lambda keyword is used to create a lambda function in python.

A lambda function is a small anonymous function. It can take any number of arguments but can only have one expression. The expression is executed and the result is returned.

You can use a lambda function to pass a simple function as an argument to another function. For example, you can use a lambda function to write a function that takes a function as an argument and calls it. Here is a simple example.

# using lambda keyword
arr = [1, 2, 3, 4, 5]
# sum of square of each element
def sum(arr):
    sum = 0
    for i in arr:
        sqr = lambda x: x**2
        sum = sum + sqr(i)
    print(sum)

sum(arr)

Output:

55

Returning keywords

You must be knowing that functions or method return something at the end of the execution. To return functions or method use 2 different keywords which has different meaning in python. Those keywords are return and yield.

The return keyword is used in all programming languages to return a value from a function or method. The yield keyword is used in python to return a value from a generator function or method. The difference between the 2 keywords is that return keyword is used to return a value from a function or method and yield keyword is used to return a value from a generator function or method.


24. return keyword

The return keyword is used to return a value from a function or method. The value returned from a function or method is assigned to a variable.

The return keyword is followed by the value that is to be returned from the function or method. Whenever a function or method encounters the return keyword, it stops executing and break out of the function or method.

A function may have more than 1 return statement based on conditions. If a function has no return statement, it returns None.

# using return keyword
def sum(a, b):
    return a + b

sum(10, 20)

Output:

30

25. yield keyword

The yield is used same as the return keyword but unlike the return keyword it does not return a value but returns a generator object.

The generator object is used to iterate over the values in a collection. You can you next() function to get the next value from the generator object.

Here is a simple example to understand the yield keyword.

# using yield keyword
def shoutName():
    yield "John"
    yield "Sara"
    yield "Mike"
    yield "Molly"

names = shoutName()

# using next() function to get the next value
print(next(names)) # John
print(next(names)) # Sara
print(next(names)) # Mike
print(next(names)) # Molly

Output:

John
Sara
Mike
Molly

The above example is simplest example of yield keyword. Here is another example that show a flow with programs.

# using yield to get even numbers
def even():
    for i in range(1, 10):
        if i % 2 == 0:
            yield i

evenNumbers = even()
for num in evenNumbers:
    print(num)

Output:

2
4
6
8