Python Keywords

Python keywords are reserved words that have predefined meanings in the language. They define the rules and structure of Python's syntax and cannot be used for any other purpose in the program, such as variable names, function names, or identifiers.

All Keywords are case sensitive and are written in lowercase except True, False and None.

As of Python version 3.8, there are 35 reserved keywords.

You can view the complete list using the keyword module


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

1. List of Keywords in Python

Keyword Explanation
and A logical operator that returns True only if both the operands are true.
as Used to create an alias while importing a module.
assert Used for debugging purposes to test if a condition in the code returns true.
async Used to define a coroutine function or an asynchronous context manager.
await Used to call a coroutine function.
break Used to exit a loop prematurely.
class Used for defining a class in object-oriented programming.
continue Used to skip the current iteration of a loop and move to the next.
def Used to define a function..
del Used to delete a reference to an object.
elif Used in conditional statements, same as else if in other programming languages.
else Used in conditional statements to define an alternative path of execution.
except Used with exceptions, contains the code that is executed if an exception occurs.
False The Boolean value of false..
finally Used with exceptions, contains a block of code that is always executed, regardless if an exception has occurred or not.
for Used to create a for loop.
from Used in import statements to import specific attributes or functions from a module.
global Used to declare a global variable.
if Used to create a conditional statement.
import Used to import modules into the current Python script.
in Used to check if a value exists in a sequence or to iterate through a sequence in a loop.
is Used to test if two variables are the same object.
lambda Used to create an anonymous function.
None Defines a null value or a void.
nonlocal Used to declare that a variable inside a nested function is not local to it, meaning it lies in the outer enclosing function.
not A logical operator that returns True if the operand is false.
or A logical operator that returns True if at least one of the operands is true.
pass A null operation; nothing happens when it executes.
raise Used to raise an exception.
return Used inside a function to exit it and return a value.
True The Boolean value of true.
try Used for exception handling to catch and handle errors.
while Used to create a while loop.
with Used to simplify exception handling by cleaning up resources and wrapping up codes that may potentially throw exceptions.
yield Used inside a function like a return statement, but yields a generator.

Let us understand each keyword using examples.

1.1. True, False, None

True, False, None are foundational to programming in Python, each serving a unique purpose.

True: This keyword represents the boolean true value in Python. It's used in logic operations and control flow.

False: False represents the boolean false value in Python. Like True, it is primarily used in logical and control flow statements.

Here's an example of its use in a simple conditional statement:


a = 10
b = 20

print(a < b)  # Output: True
print(a > b)  # Output: False

None: It is used when we want to specify that a variable exists, but it does not have a value yet. It's also a common default return value for functions. Here's an example:

It's not the same as False, zero, or any empty list. It is a datatype of its own - the NoneType. It can be used when you want to assign a variable, but you don't have an initial value for it.

For example:


def a_function():
    pass
    
result = a_function()
print(result)  # Output: None

1.2. and, or, not, in, is

and: This is a logical operator that returns True only if both operands are true. Otherwise, it returns False.

Truth table for ‘and’

A B A and B
True True True
True False False
False True False
False False False

or: This is a logical operator that returns True if at least one of the operands is true. Otherwise, it returns False.

Truth table for ‘or’

A B A and B
True True True
True False True
False True True
False False False

not: This is a logical operator that returns True if the operand is false, and False if the operand is true. It's used to reverse the logical state of its operand.

Truth table for ‘not’

A not A
True False
False True

Let see some examples below


# and 
print(True and True)  # Output: True
print(True and False)  # Output: False
    
# or
print(True or False)  # Output: True
print(False or False)  # Output: False
    
# in
print(not True)  # Output: False
print(not False)  # Output: True

in: The in keyword checks if a value is present in a sequence like a list, tuple, dictionary, string, etc.


# For a list
print(3 in [1, 2, 3])  # Output: True
print(4 in [1, 2, 3])  # Output: False
    
# For a string
print('y' in 'Python')  # Output: True
print('z' in 'Python')  # Output: False

is: The is keyword checks if both the operands refer to the same object (not if they are equal).


x = 5
y = 5
z = x
    
print(x is y)  # Output: True
print(x is z)  # Output: True
print(x is not y)  # Output: False

1.3. for, while, break, continue

for: This keyword is used in for loops, which iterate over a sequence such as a list, tuple, string, or other iterable object.


for i in range(5):
    print(i)

Output:


0
1
2
3
4

while: The while keyword is used in while loops, which continuously execute a block of code as long as a certain condition is true.


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

Output:


0
1
2
3
4

break: The break keyword is used to exit a loop prematurely. It can be used in both for and while loops.


for i in range(5):
    if i == 3:
        break
        print(i)

Output:


0
1
2

Continue: Unlike break, continue does not terminate the loop entirely; instead, it is used to skip the current iteration of a loop and immediately proceed to the next one. It can be used in both for and while loops.


for i in range(5):
    if i == 3:
        continue
    print(i)

Output:


0
1
2
4

1.4. if, else, elif

if: The if keyword is used to create a conditional statement that executes some specified code after checking if its condition is True.


a = 10
if a > 0:
    print("a is a positive number.")

Output:


a is a positive number.

else: This keyword is used to specify a block of code to be executed if the condition in the if statement is False.


a = -10
if a > 0:
    print("a is a positive number.")
else:
    print("a is not a positive number.")

Output:


a is not a positive number.

elif: The elif keyword (short for "else if") is used to specify a new condition to check for if the previous condition was False.


a = 0
if a > 0:
    print("a is a positive number.")
elif a == 0:
    print("a is zero.")
else:
    print("a is a negative number.")

Output:


a is zero.

1.5. return, yield

return: It is used in a function to signify the end of the function and to specify the result that the function should produce.


def add(a, b):
    return a + b
    
print(add(2, 3))

Output:


5

yield: The yield keyword is used in a function like a return statement, but it returns a generator—a special type of iterable that generates values on-the-fly.


def count_up_to(n):
    i = 1
    while i <= n:
        yield i
        i += 1

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

Output:


1
2
3
4
5

1.6. def, class, with, as, pass, lambda

def: The def keyword is used to define a function in Python. A function is a block of reusable code that performs a specific task.


def greet(name):
    print(f"Hello, {name}!")
    
greet("Alice")

Output:


Hello, Alice!

Class: The Class keyword is used to define a user-defined class. A class is a blueprint for creating objects in an object-oriented programming language. An object is a data structure that contains data (attributes) and methods (functions) that operate on those data. In Python, almost everything is an object - numbers, strings, lists, functions, and so on.


class Greeting:
    def __init__(self, name):
        self.name = name
    
    def greet(self):
        print(f"Hello, {self.name}!")

greeting = Greeting("Bob")
greeting.greet()

Output:


Hello, Bob!

with and as: The with statement is used in exception handling to make the code cleaner and much more readable. It simplifies the management of common resources like file streams. The as keyword is used to create an alias while importing a module, or to define a context manager in a with statement.


with open("example.txt", "w") as file:
    file.write("Hello, world!")

pass: The pass keyword is used as a placeholder for future code. When the pass statement is executed, nothing happens, but you avoid getting an error when empty code is not allowed.


def some_function():
    pass  # An empty function that will be implemented in the future

lambda: The lambda is used to create anonymous functions. This means that the function doesn't have a name. It's useful when you want to declare a small, one-time-use function that you don't want to reuse elsewhere.


square = lambda x: x ** 2
print(square(5))

Output:


25

1.7. import, from

import: It is used to import a module into your Python script. Once a module is imported, you can use its functions and classes.


import math
print(math.sqrt(16))

Output:


4.0

from: The from is used with import to import specific attributes or functions from a module, rather than importing the whole module.


from math import sqrt
print(sqrt(16))

Output:


4.0

1.8. try, except, raise, finally, assert

try and except: The try block lets you test a block of code for errors, while the except block lets you handle the error.


try:
    print(undefined_variable)
except NameError:
    print("An error occurred")

Output:


An error occurred

raise: The raise keyword is used to throw an exception. You can define what kind of error to raise, and the text to print to the user.


raise TypeError("This is a TypeError")

Output:


Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: This is a TypeError

finally: The finally block lets you execute code, regardless of the result of the try and except blocks.


try:
    print(undefined_variable)
except NameError:
    print("An error occurred")
finally:
    print("The 'try except' is finished")

Output:


An error occurred
The 'try except' is finished

assert: The assert is used when debugging code. The assert keyword lets you test if a condition in your code returns True, if not, the program will raise an AssertionError.


x = "hello"
    
# if the condition returns False, AssertionError is raised:
assert x == "goodbye", "x should be 'goodbye'"

Output:


AssertionError: x should be 'goodbye'

1.9. async, await

async: This keyword is used to declare an asynchronous function. An asynchronous function is a function that is designed to perform tasks concurrently. Asynchronous functions are defined using the async def syntax.

await: This keyword is used to call an asynchronous function and wait for it to complete. The await keyword can only be used inside an asynchronous function.


import asyncio
    
async def main():
    print('Hello')
    await asyncio.sleep(1)
    print('World')
    
# Python 3.7+
asyncio.run(main())

1.10. del, global, nonlocal

del: The del is used to delete objects. In Python, everything is an object, so the del keyword can be used to delete variables, lists, or parts of a list, dictionary items etc.


# Delete a variable
var = "Hello, World!"
del var  # var no longer exists
    
# Delete an item from a list
list_var = [1, 2, 3, 4, 5]
del list_var[1]  # list_var is now [1, 3, 4, 5]

global: The global keyword is used to declare that a variable inside the function is global (outside the function). If you need to read or write a global variable from inside a function, use the global keyword.


var = 10  # Global variable

def function():
    global var  # Reference the global variable
    var = 20  # Modify the global variable
    
function()
print(var)  # Prints 20

nonlocal: The nonlocal keyword is used to work with variables inside nested functions, where the variable should not belong to the inner function. It is used to refer to a variable of the nearest enclosing scope that is not global.


def outer_function():
    var = 10  # Belongs to outer_function
    
    def inner_function():
    	nonlocal var  # Reference the variable of outer_function
    	var = 20  # Modify the variable of outer_function
    
      inner_function()
      print(var)  # Prints 20
    
outer_function()

2. Let’s Revise

  • True, False, None: Foundational boolean values; True represents true, False represents false, and None represents a null or void value.
  • and, or, not, in, is: Logical operators for combining conditions; 'and' requires both operands to be true, 'or' returns true if at least one operand is true, 'not' reverses a condition, 'in' checks if a value is in a sequence, and 'is' tests if two variables refer to the same object.
  • for, while, break, continue: Loop control keywords; 'for' iterates over a sequence, 'while' executes code while a condition is true, 'break' exits a loop prematurely, and 'continue' skips the current iteration and moves to the next.
  • if, else, elif: Conditional keywords; 'if' tests a condition and executes code if true, 'else' defines an alternative path if the 'if' condition is false, and 'elif' adds more conditions to check.
  • return, yield: Function-related keywords; 'return' exits a function and returns a value, 'yield' returns a generator and is used in iterator functions.
  • def, class, with, as, pass, lambda: Definitions and functions; 'def' defines a function, 'class' defines a class, 'with' simplifies resource management, 'as' creates aliases, 'pass' is a placeholder for future code, and 'lambda' creates anonymous functions.
  • import, from: Module and attribute importing; 'import' brings in a module, 'from' imports specific attributes or functions from a module.
  • try, except, raise, finally, assert: Exception handling; 'try' tests code for errors, 'except' handles exceptions, 'raise' generates exceptions, 'finally' always executes code, and 'assert' checks conditions for debugging.
  • async, await: Asynchronous programming; 'async' declares asynchronous functions, and 'await' waits for asynchronous tasks to complete.
  • del, global, nonlocal: Variable management; 'del' deletes objects, 'global' declares global variables, and 'nonlocal' accesses variables in nested functions.

3. Test Your Knowledge

1. What is the purpose of the "pass" keyword in Python?
2. Which keyword is used to define an anonymous function in Python?
3. In Python, the "and" logical operator returns True if:
4. What is the purpose of the "yield" keyword in Python?
5. Which keyword is used to declare a global variable inside a function in Python?
6. In Python, what does the "assert" keyword do?
7. Which keyword is used to wait for an asynchronous task to complete in Python?
8. What is the primary purpose of the "with" keyword in Python?
Kickstart your IT career with NxtWave
Free Demo