In this article, you’ll find all Python keywords with examples that will help you understand each keyword.
After reading this article, you’ll learn:
- How to get the list of all keywords
- Understand what each keyword is used for using the help() function
- the keyword module
Table of contents
- Get the List of Keywrods
- Understand Any keyword
- How to Identify Python Keywords
- Keyword Module
- Types of Keywords
- Value Keywords: True, False, None.
- Operator Keywords: and, or, not, in, is
- Conditional Keywords: if, elif, else
- Iterative and Transfer Keywords: for, while, break, continue, else
- Structure Keywords: def, class, with, as, pass, lambda
- Import Keywords: import, from, as
- Returning Keywords: return, yield
- Exception-Handling Keywords: try, except, raise, finally, else, assert
- Variable Handling Keywords: del, global, nonlocal
- Asynchronous Programming Keywords: async, await
What is keyword in Python?
Python keywords are reserved words that have a special meaning associated with them and can’t be used for anything but those specific purposes. Each keyword is designed to achieve specific functionality.
Python keywords are case-sensitive.
- All keywords contain only letters (no special symbols)
- Except for three keywords (
True,False,None), all keywords have lower case letters
Get the List of Keywrods
As of Python 3.9.6, there are 36 keywords available. This number can vary slightly over time.
We can use the following two ways to get the list of keywords in Python
- keyword module: The keyword is the buil-in module to get the list of keywords. Also, this module allows a Python program to determine if a string is a keyword.
help()function: Apart from a keyword module, we can use thehelp()function to get the list of keywords
Example: keyword module
import keyword
print(keyword.kwlist)Code language: Python (python)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']
All the keywords except, True, False, and None, must be written in a lowercase alphabet symbol.
Example 2: The help() function
help("keywords")Code language: Python (python)Output:
Here is a list of the Python keywords. Enter any keyword to get more help. False break for not None class from or True continue global pass __peg_parser__ def if raise and del import return as elif in try assert else is while async except lambda with await finally nonlocal yield
Note:
You cannot use any of the above keywords as identifiers in your programs. If you try to do so, you will get an error. An identifier is a name given to an entity, For example, variables name, functions name, or class name.
Understand Any keyword
The python help() function is used to display the documentation of modules, functions, classes, keywords.
Pass the keyword name to the help() function to get to know how to use it. The help() function returns the description of a keyword along with an example.
Let’s understand how to use the if keyword.
Example:
print(help('if'))Code language: Python (python)Output:
The "if" statement
******************
The "if" statement is used for conditional execution:
if_stmt ::= "if" assignment_expression ":" suite
("elif" assignment_expression ":" suite)*
["else" ":" suite]
It selects exactly one of the suites by evaluating the expressions one
by one until one is found to be true (see section Boolean operations
for the definition of true and false); then that suite is executed
(and no other part of the "if" statement is executed or evaluated).
If all expressions are false, the suite of the "else" clause, if
present, is executed.
How to Identify Python Keywords
Keywords are mostly highlighted in IDE when you write a code. This will help you identify Python keywords while you’re writing a code so you don’t use them incorrectly.
An integrated development environment (IDE) is software or a code editor for building applications that combine standard developer tools into a single graphical user interface (GUI). An IDE typically consists of a source editor, syntax highlighting, debugger, and build tools.
Python provides an IDLE that comes with Python installation. In IDLE, keywords are highlighted in a specific color. You can also use third-party editors such as Python IntelliJ IDEA or eclipse ide.
Image
Another way is if you are getting a syntax error for any identifier declaration, then you may be using a keyword as an identifier in your program.
Keyword Module
Python keyword module allows a Python program to determine if a string is a keyword.
iskeyword(s): Returns True if s is a keyword
Example:
import keyword
print(keyword.iskeyword('if'))
print(keyword.iskeyword('range'))Code language: Python (python)Output:
As you can see in the output, it returned True because ‘if’ is the keyword, and it returned False because the range is not a keyword (it is a built-in function).
Also, keyword module provides following functions to identify keywords.
keyword.kwlist:It return a sequence containing all the keywords defined for the interpreter.keyword.issoftkeyword(s): ReturnTrueif s is a Python soft keyword. New in version 3.9keyword.softkwlist: Sequence containing all the soft keywords defined for the interpreter. New in version 3.9
Types of Keywords
All 36 keywords can be divided into the following seven categories.
Value Keywords: True, False, None.
True and False are used to represent truth values, know as boolean values. It is used with a conditional statement to determine which block of code to execute. When executed, the condition evaluates to True or False.
Example:
x = 25
y = 20
z = x > y
print(z) # True
Code language: Python (python)Operator Keywords: and, or, not, in, is
- The logical
andkeyword returnsTrueif both expressions are True. Otherwise, it will return.False. - The logical
orkeyword returns a booleanTrueif one expression is true, and it returnsFalseif both values arefalse. - The logical
notkeyword returns booleanTrueif the expression isfalse.
See Logical operators in Python
Example:
x = 10
y = 20
# and to combine to conditions
# both need to be true to execute if block
if x > 5 and y < 25:
print(x + 5)
# or condition
# at least 1 need to be true to execute if block
if x > 5 or y < 100:
print(x + 5)
# not condition
# condition must be false
if not x:
print(x + 5)Code language: Python (python)Output:
15 15
The is keyword returns return True if the memory address first value is equal to the second value. Read Identity operators in Python.
Example: is keyword
# is keyword demo
x = 10
y = 11
z = 10
print(x is y) # it compare memory address of x and y
print(x is z) # it compare memory address of x and zCode language: Python (python)Output:
False
True
The in keyword returns True if it finds a given object in the sequence (such as list, string). Read membership operators in Python
Example: in Keyword
my_list = [11, 15, 21, 29, 50, 70]
number = 15
if number in my_list:
print("number is present")
else:
print("number is not present")Code language: Python (python)Output:
number is present
Conditional Keywords: if, elif, else
In Python, condition keywords act depending on whether a given condition is true or false. You can execute different blocks of codes depending on the outcome of a condition.
Example:
x = 75
if x > 100:
print('x is greater than 100')
elif x > 50:
print('x is greater than 50 but less than 100')
else:
print('x is less than 50')Code language: Python (python)Output:
x is greater than 50 but less than 100
Iterative and Transfer Keywords: for, while, break, continue, else
Iterative keywords allow us to execute a block of code repeatedly. We also call it a loop statements.
while: The while loop repeatedly executes a code block while a particular condition is true.for: Using for loop, we can iterate any sequence or iterable variable. The sequence can be string, list, dictionary, set, or tuple.
Example:
print('for loop to display first 5 numbers')
for i in range(5):
print(i, end=' ')
print('while loop to display first 5 numbers')
n = 0
while n < 5:
print(n, end=' ')
n = n + 1Code language: Python (python)Output:
for loop to display first 5 numbers 0 1 2 3 4 while loop to display first 5 numbers 0 1 2 3 4
break, continue, and pass: In Python, transfer statements are used to alter the program’s way of execution in a certain manner. Read break and continue in Python.
Structure Keywords: def, class, with, as, pass, lambda
The def keyword is used to define user-defined funtion or methods of a class
Example: def keyword
# def keyword: create function
def addition(num1, num2):
print('Sum is', num1 + num2)
# call function
addition(10, 20)
Code language: Python (python)Output:
Sum is 30
Jessa 19
The pass keyword is used to define as a placeholder when a statement is required syntactically.
Example: pass keyword
# pass keyword: create syntactically empty function
# code to add in future
def sub(num1, num2):
passCode language: Python (python)class keyword is sued to define class in Python. Object-oriented programming (OOP) is a programming paradigm based on the concept of “objects“. An object-oriented paradigm is to design the program using classes and objects
Example: class keyword
# create class
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def show(self):
print(self.name, self.age)
# create object
s = Student('Jessa', 19)
# call method
s.show()Code language: Python (python)Output:
Jessa 19
with keyword is used when working with unmanaged resources (like file streams). It allows you to ensure that a resource is “cleaned up” when the code that uses it finishes running, even if exceptions are thrown.
Example: Open a file in Python uisng the with statement
# Opening file
with open('sample.txt', 'r', encoding='utf-8') as fp:
# read sample.txt
print(fp.read())Code language: Python (python)Import Keywords: import, from, as
In Python, the import statement is used to import the whole module.
Example: Import Python datetime module
import datetime
# get current datetime
now = datetime.datetime.now()
print(now)
Code language: Python (python)Also, we can import specific classes and functions from a module.
Example:
# import only datetime class
from datetime import datetime
# get current datetime
now = datetime.now()
print(now)
Code language: Python (python)Returning Keywords: return, yield
- In Python, to return value from the function, a
returnstatement is used. yieldis a keyword that is used likereturn, except the function will return a generator. See yield keyword
Example:
def addition(num1, num2):
return num1 + num2 # return sum of two number
# call function
print('Sum:', addition(10, 20))
Code language: Python (python)Output:
Sum: 30
Exception-Handling Keywords: try, except, raise, finally, else, assert
An exception is an event that occurs during the execution of programs that disrupt the normal flow of execution (e.g., KeyError Raised when a key is not found in a dictionary.) An exception is a Python object that represents an error.
Read Exception handling in Python
Variable Handling Keywords: del, global, nonlocal
- The
delkeyword is used to delete the object. - The
globalkeyword is used to declare the global variable. A global variable is a variable that is defined outside of the method (block of code). That is accessible anywhere in the code file. - Nonlocal variables are used in nested functions whose local scope is not defined. This means that the variable can be neither in the local nor the global scope.
Example:
price = 900 # Global variable
def test1(): # defining 1st function
print("price in 1st function :", price) # 900
def test2(): # defining 2nd function
print("price in 2nd function :", price) # 900
# call functions
test1()
test2()
# delete variable
del priceCode language: Python (python)Asynchronous Programming Keywords: async, await
The async keyword is used with def to define an asynchronous function, or coroutine.
async def <function>(<params>):
<statements>Code language: Python (python)
Also, you can make a function asynchronous by adding the async keyword before the function’s regular definition.
Python’s await keyword is used in asynchronous functions to specify a point in the function where control is given back to the event loop for other functions to run. You can use it by placing the await keyword in front of a call to any async function:
await <some async function call>
# OR
<var> = await <some async function call>Code language: Python (python)
See: Coroutines and Tasks
