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 (
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 the
help()function to get the list of keywords
Example: keyword module
import keyword print(keyword.kwlist)
['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,
None, must be written in a lowercase alphabet symbol.
Example 2: The
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
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
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
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.
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.
Python keyword module allows a Python program to determine if a string is a keyword.
s is a keyword
import keyword print(keyword.iskeyword('if')) print(keyword.iskeyword('range'))
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.
Trueif s is a Python soft keyword. New in version 3.9
keyword.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.
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
x = 25 y = 20 z = x > y print(z) # True
- The logical
Trueif both expressions are True. Otherwise, it will return.
- The logical
orkeyword returns a boolean
Trueif one expression is true, and it returns
Falseif both values are
- The logical
notkeyword returns boolean
Trueif the expression is
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)
is keyword returns return
True if the memory address first value is equal to the second value. Read Identity operators in Python.
# 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 z
in keyword returns
True if it finds a given object in the sequence (such as list, string). Read membership operators in Python
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")
number is present
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.
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')
x is greater than 50 but less than 100
Iterative and Transfer Keywords:
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.
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 + 1
for loop to display first 5 numbers 0 1 2 3 4 while loop to display first 5 numbers 0 1 2 3 4
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.
# def keyword: create function def addition(num1, num2): print('Sum is', num1 + num2) # call function addition(10, 20)
Sum is 30
# pass keyword: create syntactically empty function # code to add in future def sub(num1, num2): pass
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
# 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()
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
# Opening file with open('sample.txt', 'r', encoding='utf-8') as fp: # read sample.txt print(fp.read())
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)
Also, we can import specific classes and functions from a module.
# import only datetime class from datetime import datetime # get current datetime now = datetime.now() print(now)
- In Python, to return value from the function, a
returnstatement is used.
yieldis a keyword that is used like
return, except the function will return a generator. See yield keyword
def addition(num1, num2): return num1 + num2 # return sum of two number # call function print('Sum:', addition(10, 20))
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.
Variable Handling Keywords:
delkeyword is used to delete the object.
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.
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 price
Asynchronous Programming Keywords:
async keyword is used with
def to define an asynchronous function, or coroutine.
async def <function>(<params>): <statements>
Also, you can make a function asynchronous by adding the
async keyword before the function’s regular definition.
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
await <some async function call> # OR <var> = await <some async function call>
See: Coroutines and Tasks