Python Search Terms
| 2 Comments | Updated on: August 31, 2021
This page contains a list of all Python keywords, along with examples to help you understand each one.
You will learn the following after reading this article:
The following is a table of contents.
- 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 exactly is a keyword in Python?
Python keywords are reserved words that have a defined meaning and cannot be used for anything other than those uses. Each keyword is intended to perform a certain purpose.
Case matters when it comes to Python keywords.
True
, False
, None
), all keywords have lower case lettersDownload the Keywrod List
There are 36 keywords available as of Python 3.9.6. This figure may change somewhat over time.
In Python, we have two options for getting a list of keywords.
help()
function: Apart from a keyword module, we can use the help()
function to get the list of keywordsKeyword 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’]
Apart for True, False, and None, all keywords must be typed in lowercase letter symbols.
Exemplification 2: The help() method 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
Please keep in mind that you cannot use any of the aforementioned keywords as IDs in your applications. If you attempt, you will get an error. An identifier is a name provided to an entity, such as variables, functions, or classes.
Recognize any keyword
The help() method in Python is used to show documentation for modules, functions, classes, and keywords.
To learn how to use a keyword, provide its name to the help() method. The help() method produces a keyword description as well as an example.
Let’s look at how to utilise the if keyword.
Example:
print(help('if'))
Output:
The “if” statement
How to Find Python Keywords
As you write code, keywords are generally highlighted in the IDE. This will assist you in identifying Python keywords when creating code so that you do not use them erroneously.
An integrated development environment (IDE) is a piece of software or a code editor that combines conventional developer tools into a single graphical user interface (GUI). An integrated development environment (IDE) often includes a source editor, syntax highlighting, a debugger, and build tools.
Python includes an IDLE with the installation of the language. IDLE highlights terms in a certain colour. Third-party editors, such as Python IntelliJ IDEA or Eclipse IDE, are also available.
Image
Another method is to use a keyword as an identifier in your programme if you get a syntax error for any identifier declaration.
Module for Keywords
A Python application may use the keyword module to detect if a string is a keyword.
iskeyword(s): Returns If s is a keyword, this is true.
Example:
import keyword
print(keyword.iskeyword('if'))
print(keyword.iskeyword('range'))
Output:
As seen in the output, it returned Yes since the keyword is ‘if,’ and False because the range is not a keyword (it is a built-in function).
In addition, the keyword module contains the following functions for identifying keywords.
keyword.kwlist:
It return a sequence containing all the keywords defined for the interpreter.keyword.issoftkeyword(s)
: Return True
if 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.9Keyword Types
All 36 keywords may be classified into the seven groups listed below.
True, False, and None are the value keywords.
True and False are boolean values that reflect truth values. It is used in conjunction with a conditional statement to decide which block of code should be executed. When the condition is run, it returns True or False.
Example:
x = 25
y = 20
z = x > y
print(z) # True
Keywords for operators: and, or, not, in, is
and
keyword returns True
if both expressions are True. Otherwise, it will return. False
.or
keyword returns a boolean True
if one expression is true, and it returns False
if both values are false
.not
keyword returns boolean True
if the expression is false
.See Python logical operators 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)
Output:
The keyword is returns return True if the first and second values of the memory address are the same. Identity operators in Python can be found here.
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 z
Output:
If the in keyword detects a specified item in the sequence, it returns True (such as list, string). In Python, read membership operators as follows: 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")
Output:
If, elif, and else are conditional keywords.
Condition keywords in Python take action based on whether a particular condition is true or false. Depending on the conclusion of a condition, you may run various pieces of code.
See also: Python Control Flow
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')
Output:
Keywords for iterative and transfer: for, while, break, continue, otherwise
Iterative keywords enable us to run a section of code several times. It is also known as a loop statement.
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 + 1
Output:
break, continue, and pass: In Python, transfer statements are used to change the way the programme executes. In Python, see break and continue.
Keywords: define, class, with, as, pass, lambda
The def keyword is used to declare a class’s user-defined functions or methods.
Define keyword
help("keywords")
0 Output:
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.
When a statement is needed syntactically, the pass keyword is used to specify it as a placeholder.
In Python, the pass keyword
help("keywords")
1 class keyword is used to define a class. Object-oriented programming (OOP) is a programming paradigm that is built on the idea of “objects”. The application is designed using classes and objects in an object-oriented paradigm.
For instance, class keyword
help("keywords")
2
Output:
15
15
When interacting with unmanaged resources, the with keyword is utilised (like file streams). It enables you to assure that a resource is “cleaned up” after the code that utilises it completes, even if exceptions are raised.
Use the with statement to open a file in Python.
help("keywords")
3
Keywords for Import: import, from, as
The import line in Python is used to import the whole module.
Import Python datetime module
help("keywords")
4 as an example
We may also import individual classes and functions from modules.
Example:
help("keywords")
5
Keywords for Returning: return, yield
return
statement is used.yield
is a keyword that is used like return
, except the function will return a generator. See yield keywordExample:
help("keywords")
6
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
0
Keywords for Exception Handling: try, except, raise, finally, otherwise, assert
An exception is an occurrence during programme execution that disrupts the regular flow of execution (e.g., KeyError Raised when a key is not found in a dictionary.) A Python object that reflects an error is known as an exception.
Read Exception Handling in Python @@@7 Keywords: del, global, nonlocal
del
keyword is used to delete the object.global
keyword 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.Example:
help("keywords")
7
Keywords for Asynchronous Programming: async, await
The async keyword is used in conjunction with def to create an asynchronous function, often known as a coroutine.
help("keywords")
8 You may also make a function asynchronous by using the async keyword before its usual definition.
The waiting keyword
In asynchronous functions, the await keyword is used to identify a point in the function when control is returned to the event loop for other functions to perform. You may use it by adding the await keyword to any async function call:
help("keywords")
9
Check out Coroutines and Tasks.
Filed Under: Python, Python Fundamentals