Python Keywords
Python Keywords
Table of Contents
Python Keywords
How to Identify Python Keywords
o Use an IDE With Syntax Highlighting
o Use Code in a REPL to Check Keywords
o Look for a SyntaxError
Python Keywords and Their Usage
o Value Keywords: True, False, None
o Operator Keywords: and, or, not, in, is
o Control Flow Keywords: if, elif, else
o Iteration Keywords: for, while, break, continue, else
o Structure Keywords: def, class, with, as, pass, lambda
o Returning Keywords: return, yield
o Import Keywords: import, from, as
o Exception-Handling Keywords: try, except, raise, finally, else, assert
o Asynchronous Programming Keywords: async, await
o Variable Handling Keywords: del, global, nonlocal
Every programming language has special reserved words, or keywords, that have
specific meanings and restrictions around how they should be used. Python is no
different. Python keywords are the fundamental building blocks of any Python program.
In this article, you’ll find a basic introduction to all Python keywords along with other
resources that will be helpful for learning more about each keyword.
Python Keywords
Python keywords are special reserved words that have specific meanings and purposes
and can’t be used for anything but those specific purposes. These keywords are always
available—you’ll never have to import them into your code.
Python keywords are different from Python’s built-in functions and types. The built-in
functions and types are also always available, but they aren’t as restrictive as the
keywords in their usage.
An example of something you can’t do with Python keywords is assign something to
them. If you try, then you’ll get a SyntaxError. You won’t get a SyntaxError if you try to
assign something to a built-in function or type, but it still isn’t a good idea. For a more
in-depth explanation of ways keywords can be misused, check out Invalid Syntax in
Python: Common Reasons for SyntaxError.
As of Python 3.8, there are thirty-five keywords in Python. Here they are with links to the
relevant sections throughout the rest of this article:
Note: Two keywords have additional uses beyond their initial use cases.
The else keyword is also used with loops as well as with try and except. The as keyword is
also used with the with keyword.
In the sections below, you’ll learn several ways to know or find out which words are
keywords in Python.
There are a lot of good Python IDEs out there. All of them will highlight keywords to
differentiate them from other words in your code. This will help you quickly identify
Python keywords while you’re programming so you don’t use them incorrectly.
In the Python REPL, there are a number of ways you can identify valid Python keywords
and learn more about them.
Note: Code examples in this article use Python 3.8 unless otherwise indicated.
You can get a list of available keywords by using help():
>>>
>>> help("keywords")
Here is a list of the Python keywords. Enter any keyword to get more help.
>>>
>>> help("pass")
The "pass" statement
********************
1. kwlist provides a list of all the Python keywords for the version of Python you’re
running.
2. iskeyword() provides a handy way to determine if a string is also a keyword.
To get a list of all the keywords in the version of Python you’re running, and to quickly
determine how many keywords are defined, use [Link]:
>>>
>>> import keyword
>>> [Link]
['False', 'None', 'True', 'and', 'as', 'assert', 'async', ...
>>> len([Link])
35
If you need to know more about a keyword or need to work with keywords in a
programmatic way, then Python provides this documentation and tooling for you.
Finally, another indicator that a word you’re using is actually a keyword is if you get
a SyntaxError while trying to assign to it, name a function with it, or do something else
that isn’t allowed with it. This one is a little harder to spot, but it’s a way that Python will
let you know you’re using a keyword incorrectly.
There are a few terms used in the sections below that may be new to you. They’re
defined here, and you should be aware of their meaning before proceeding:
The True keyword is used as the Boolean true value in Python code. The Python
keyword False is similar to the True keyword, but with the opposite Boolean value of
false. In other programming languages, you’ll see these keywords written in lowercase
(true and false), but in Python they are always written in uppercase.
The Python keywords True and False can be assigned to variables and compared to
directly:
>>>
>>> x = True
>>> x is True
True
>>> y = False
>>> y is False
True
Most values in Python will evaluate to True when passed to bool(). There are only a few
values in Python that will evaluate to False when passed to bool(): 0, "", [], and {} to
name a few. Passing a value to bool() indicates the value’s truthiness, or the equivalent
Boolean value. You can compare a value’s truthiness to True or False by passing the
value to bool():
>>>
>>> x = "this is a truth value"
>>> x is True
False
>>> bool(x) is True
True
>>>
>>> x = "this is a truth value"
>>> if x is True: # Don't do this
... print("x is True")
...
>>> if x: # Do this
... print("x is truth")
...
x is truth
In Python, you generally don’t need to convert values to be explicitly True or False.
Python will implicitly determine the truthiness of the value for you.
The Python keyword None represents no value. In other programming languages, None is
represented as null, nil, none, undef, or undefined.
None is also the default value returned by a function if it doesn’t have a return statement:
>>>
>>> def func():
... print("hello")
...
>>> x = func()
hello
>>> print(x)
None
Several Python keywords are used as operators. In other programming languages, these
operators use symbols like &, |, and !. The Python operators for these are all keywords:
The Python keyword and is used to determine if both the left and right operands are
truthy or falsy. If both operands are truthy, then the result will be truthy. If one is falsy,
then the result will be falsy:
If you wanted to define an expression that did the same thing as an and expression, but
without using the and keyword, then you could use the Python ternary operator:
Because and returns the first operand if it’s falsy and otherwise returns the last operand,
you can also use and in an assignment:
x = y and z
If y is falsy, then this would result in x being assigned the value of y. Otherwise, x would
be assigned the value of z. However, this makes for confusing code. A more verbose
and clear alternative would be:
x = y if not y else z
This code is longer, but it more clearly indicates what you’re trying to accomplish.
The or Keyword
<expr1> or <expr2>
Just like the and keyword, or doesn’t convert its operands to their Boolean values.
Instead, it relies on their truthiness to determine the results.
If you wanted to write something like an or expression without the use of or, then you
could do so with a ternary expression:
For a more in-depth look at or, you can read about how to use the Python or operator.
Python’s not keyword is used to get the opposite Boolean value of a variable:
>>>
>>> val = "" # Truthiness value is `False`
>>> not val
True
If you wanted to get the same behavior without using not, then you could do so with
the following ternary expression:
The in Keyword
<element> in <container>
A good example of using the in keyword is checking for a specific letter in a string:
>>>
>>> name = "Chad"
>>> "c" in name
False
>>> "C" in name
True
The in keyword works with all types of containers: lists, dicts, sets, strings, and anything
else that defines __contains__() or can be iterated over.
The is Keyword
Python’s is keyword is an identity check. This is different from the == operator, which
checks for equality. Sometimes two things can be considered equal but not be the exact
same object in memory. The is keyword determines whether two objects are exactly the
same object:
<obj1> is <obj2>
This will return True if <obj1> is the exact same object in memory as <obj2>, or else it will
return False.
Most of the time you’ll see is used to check if an object is None. Since None is a singleton,
only one instance of None that can exist, so all None values are the exact same object in
memory.
If these concepts are new to you, then you can get a more in-depth explanation by
checking out Python ‘!=’ Is Not ‘is not’: Comparing Objects in Python. For a deeper dive into
how is works, check out Operators and Expressions in Python.
Three Python keywords are used for control flow: if, elif, and else. These Python
keywords allow you to use conditional logic and execute code given certain conditions.
These keywords are very common—they’ll be used in almost every program you see or
write in Python.
The if Keyword
The syntax for an if statement starts with the keyword if at the beginning of the line,
followed by a valid expression that will be evaluated for its truthiness value:
if <expr>:
<statements>
The if statement is a crucial component of most programs.
if <expr2>:
<var> = <expr1>
else:
<var> = <expr3>
If your expressions are uncomplicated statements, then using the ternary expression
provides a nice way to simplify your code a bit. Once the conditions get a little complex,
it’s often better to rely on the standard if statement.
The elif statement looks and functions like the if statement, with two major
differences:
if <expr1>:
<statements>
elif <expr2>:
<statements>
elif <expr3>:
<statements>
Python doesn’t have a switch statement. One way to get the same functionality that
other programming languages provide with switch statements is by using if and elif.
For other ways of reproducing the switch statement in Python, check out Emulating
switch/case Statements in Python.
The else statement, in conjunction with the Python keywords if and elif, denotes a
block of code that should be executed only if the other conditional blocks, if and elif,
are all falsy:
if <expr>:
<statements>
else:
<statements>
Notice that the else statement doesn’t take a conditional expression. Knowledge of
the elif and else keywords and their proper usage is critical for Python programmers.
Together with if, they make up some of the most frequently used components in any
Python program.
Iteration Keywords: for, while, break, continue, else
Looping and iteration are hugely important programming concepts. Several Python
keywords are used to create and work with loops. These, like the Python keywords used
for conditionals above, will be used and seen in just about every Python program you
come across. Understanding them and their proper usage will help you improve as a
Python programmer.
The most common loop in Python is the for loop. It’s constructed by combining the
Python keywords for and in explained earlier. The basic syntax for a for loop is as
follows:
>>>
>>> for num in range(1, 6):
... print(num)
...
1
2
3
4
5
In other programming languages, the syntax for a for loop will look a little different.
You’ll often need to specify the variable, the condition for continuing, and the way to
increment that variable (for (int i = 0; i < 5; i++)).
In Python, the for loop is like a for-each loop in other programming languages. Given the
object to iterate over, it assigns the value of each iteration to the variable:
>>>
>>> people = ["Kevin", "Creed", "Jim"]
>>> for person in people:
... print(f"{person} was in The Office.")
...
Kevin was in The Office.
Creed was in The Office.
Jim was in The Office.
In this example, you start with the list (container) of people’s names. The for loop starts
with the for keyword at the beginning of the line, followed by the variable to assign
each element of the list to, then the in keyword, and finally the container (people).
Python’s while loop uses the keyword while and works like a while loop in other
programming languages. As long as the condition that follows the while keyword is
truthy, the block following the while statement will continue to be executed over and
over again:
while <expr>:
<statements>
Note: For the infinite loop example below, be prepared to use Ctrl + C to stop the
process if you decide to try it on your own machine.
The easiest way to specify an infinite loop in Python is to use the while keyword with an
expression that is always truthy:
>>>
>>> while True:
... print("working...")
...
If you need to exit a loop early, then you can use the break keyword. This keyword will
work in both for and while loops:
>>>
>>> nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> total_sum = 0
>>> for num in nums:
... total_sum += num
... if total_sum > 10:
... break
...
>>> total_sum
15
Both the Python keywords break and continue can be useful tools when working with
loops.
Python also has a continue keyword for when you want to skip to the next loop
iteration. Like in most other programming languages, the continue keyword allows you
to stop executing the current loop iteration and move on to the next iteration:
In addition to using the else keyword with conditional if statements, you can also use it
as part of a loop. When used with a loop, the else keyword specifies code that should
be run if the loop exits normally, meaning break was not called to exit the loop early.
The syntax for using else with a for loop looks like the following:
while <expr>:
<statements>
else:
<statements>
The Python standard documentation has a section on using break and else with
a for loop that you should really check out. It uses a great example to illustrate the
usefulness of the else block.
The task it shows is looping over the numbers two through nine to find the prime
numbers. One way you could do this is with a standard for loop with a flag variable:
>>>
>>> for n in range(2, 10):
... prime = True
... for x in range(2, n):
... if n % x == 0:
... prime = False
... print(f"{n} is not prime")
... break
... if prime:
... print(f"{n} is prime!")
...
2 is prime!
3 is prime!
4 is not prime
5 is prime!
6 is not prime
7 is prime!
8 is not prime
9 is not prime
You can use the prime flag to indicate how the loop was exited. If it exited normally,
then the prime flag stays True. If it exited with break, then the prime flag will be set
to False. Once outside the inner for loop, you can check the flag to determine
if prime is True and, if so, print that the number is prime.
The else block provides more straightforward syntax. If you find yourself having to set a
flag in a loop, then consider the next example as a way to potentially simplify your
code:
>>>
>>> for n in range(2, 10):
... for x in range(2, n):
... if n % x == 0:
... print(f"{n} is not prime")
... break
... else:
... print(f"{n} is prime!")
...
2 is prime!
3 is prime!
4 is not prime
5 is prime!
6 is not prime
7 is prime!
8 is not prime
9 is not prime
The only thing that you need to do to use the else block in this example is to remove
the prime flag and replace the final if statement with the else block. This ends up
producing the same result as the example before, only with clearer code.
Sometimes using an else keyword with a loop can seem a little strange, but once you
understand that it allows you to avoid using flags in your loops, it can be a powerful
tool.
def <function>(<params>):
<body>
Functions and methods can be very helpful structures in any Python program. To learn
more about defining them and all their ins and outs, check out Defining Your Own Python
Function.
To define a class in Python, you use the class keyword. The general syntax for defining
a class with class is as follows:
class MyClass(<extends>):
<body>
Classes are powerful tools in object-oriented programming, and you should know
about them and how to define them..
Context managers are a really helpful structure in Python. Each context manager
executes specific code before and after the statements you specify. To use one, you use
the with keyword:
If you wanted to open a file, do something with that file, and then make sure that the file
was closed correctly, then you would use a context manager. Consider this example in
which [Link] contains a list of names, one per line:
>>>
>>> with open("[Link]") as input_file:
... for name in input_file:
... print([Link]())
...
Jim
Pam
Cece
Philip
The file I/O context manager provided by open() and initiated with the with keyword
opens the file for reading, assigns the open file pointer to input_file, then executes
whatever code you specify in the with block. Then, after the block is executed, the file
pointer closes. Even if your code in the with block raises an exception, the file pointer
would still close.
If you want access to the results of the expression or context manager passed to with,
you’ll need to alias it using as. You may have also seen as used to alias imports and
exceptions, and this is no different. The alias is available in the with block:
Since Python doesn’t have block indicators to specify the end of a block,
the pass keyword is used to specify that the block is intentionally left blank. It’s the
equivalent of a no-op, or no operation. Here are a few examples of using pass to
specify that the block is blank:
def my_function():
pass
class MyClass:
pass
if True:
pass
The lambda keyword is used to define a function that doesn’t have a name and has only
one statement, the results of which are returned. Functions defined with lambda are
referred to as lambda functions:
def p10(x):
return x**10
One common use for a lambda function is specifying a different behavior for another
function. For example, imagine you wanted to sort a list of strings by their integer
values. The default behavior of sorted() would sort the strings alphabetically. But
with sorted(), you can specify which key the list should be sorted on.
>>>
>>> ids = ["id1", "id2", "id30", "id3", "id20", "id10"]
>>> sorted(ids)
['id1', 'id10', 'id2', 'id20', 'id3', 'id30']
For comparison, this is what the example above would look like without using lambda:
>>>
>>> def sort_by_int(x):
... return int(x[2:])
...
>>> ids = ["id1", "id2", "id30", "id3", "id20", "id10"]
>>> sorted(ids, key=sort_by_int)
['id1', 'id2', 'id3', 'id10', 'id20', 'id30']
This code produces the same result as the lambda example, but you need to define the
function before using it.
For a lot more information about lambda, check out How to Use Python Lambda Functions.
There are two Python keywords used to specify what gets returned from functions or
methods: return and yield. Understanding when and where to use return is vital to
becoming a better Python programmer. The yield keyword is a more advanced feature
of Python, but it can also be a useful tool to understand.
Python’s return keyword is valid only as part of a function defined with def. When
Python encounters this keyword, it will exit the function at that point and return the
results of whatever comes after the return keyword:
def <function>():
return <expr>
When given no expression, return will return None by default:
>>>
>>> def return_none():
... return
...
>>> return_none()
>>> r = return_none()
>>> print(r)
None
Most of the time, however, you want to return the results of an expression or a specific
value:
>>>
>>> def plus_1(num):
... return num + 1
...
>>> plus_1(9)
10
>>> r = plus_1(9)
>>> print(r)
10
You can even use the return keyword multiple times in a function. This allows you to
have multiple exit points in your function. A classic example of when you would want to
have multiple return statements is the following recursive solution to calculating factorial:
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n - 1)
In the factorial function above, there are two cases in which you would want to return
from the function. The first is the base case, when the number is 1, and the second is
the regular case, when you want to multiply the current number by the next number’s
factorial value.
To learn more about the return keyword, check out Defining Your Own Python Function.
Python’s yield keyword is kind of like the return keyword in that it specifies what gets
returned from a function. However, when a function has a yield statement, what gets
returned is a generator. The generator can then be passed to Python’s built-
in next() to get the next value returned from the function.
When you call a function with yield statements, Python executes the function until it
reaches the first yield keyword and then returns a generator. These are known as
generator functions:
def <function>():
yield <expr>
The most straightforward example of this would be a generator function that returns
the same set of values:
>>>
>>> def family():
... yield "Pam"
... yield "Jim"
... yield "Cece"
... yield "Philip"
...
>>> names = family()
>>> names
<generator object family at 0x7f47a43577d8>
>>> next(names)
'Pam'
>>> next(names)
'Jim'
>>> next(names)
'Cece'
>>> next(names)
'Philip'
>>> next(names)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
Once the StopIteration exception is raised, the generator is done returning values. In
order to go through the names again, you would need to call family() again and get a
new generator. Most of the time, a generator function will be called as part of
a for loop, which does the next() calls for you.
For much more on the yield keyword and using generators and generator functions,
check out How to Use Generators and yield in Python and Python Generators 101.
For those tools that, unlike Python keywords and built-ins, are not already available to
your Python program, you’ll need to import them into your program. There are many
useful modules available in Python’s standard library that are only an import away.
There are also many other useful libraries and tools available in PyPI that, once you’ve
installed them into your environment, you’ll need to import into your programs.
The following are brief descriptions of the three Python keywords used for importing
modules into your program.
Python’s import keyword is used to import, or include, a module for use in your Python
program. Basic usage syntax looks like this:
import <module>
After that statement runs, the <module> will be available to your program.
For example, if you want to use the Counter class from the collections module in the
standard library, then you can use the following code:
>>>
>>> import collections
>>> [Link]()
Counter()
Importing collections in this way makes the whole collections module, including
the Counter class, available to your program. By using the module name, you have
access to all the tools available in that module. To get access to Counter, you reference it
from the module: [Link].
The from keyword is used together with import to import something specific from a
module:
If you want to use Counter from the collections module in the standard library, then you
can import it specifically:
>>>
>>> from collections import Counter
>>> Counter()
Counter()
Importing Counter like this makes the Counter class available, but nothing else from
the collections module is available. Counter is now available without you having to
reference it from the collections module.
The as Keyword
The as keyword is used to alias an imported module or tool. It’s used together with the
Python keywords import and from to change the name of the thing being imported:
If you want to import the Counter class from the collections module but name it
something different, you can alias it by using as:
>>>
>>> from collections import Counter as C
>>> C()
Counter()
Now Counter is available to be used in your program, but it’s referenced by C instead. A
more common use of as import aliases is with NumPy or Pandas packages. These are
commonly imported with standard aliases:
import numpy as np
import pandas as pd
This is a better alternative to just importing everything from a module, and it allows you
to shorten the name of the module being imported.
One of the most common aspects of any Python program is the raising and catching of
exceptions. Because this is such a fundamental aspect of all Python code, there are
several Python keywords available to help make this part of your code clear and
concise.
The sections below go over these Python keywords and their basic usage. For a more
in-depth tutorial on these keywords, check out Python Exceptions: An Introduction.
Any exception-handling block begins with Python’s try keyword. This is the same in
most other programming languages that have exception handling.
The code in the try block is code that might raise an exception. Several other Python
keywords are associated with try and are used to define what should be done if
different exceptions are raised or in different situations. These are except, else,
and finally:
try:
<statements>
<except|else|finally>:
<statements>
A try block isn’t valid unless it has at least one of the other Python keywords used for
exception handling as part of the overall try statement.
If you wanted to calculate and return the miles per gallon of gas (mpg) given the miles
driven and the gallons of gas used, then you could write a function like the following:
Python’s except keyword is used with try to define what to do when specific exceptions
are raised. You can have one or more except blocks with a single try. The basic usage
looks like this:
try:
<statements>
except <exception>:
<statements>
Taking the mpg() example from before, you could also do something specific in the
event that someone passes types that won’t work with the / operator. Having
defined mpg() in a previous example, now try to call it with strings instead of numbers:
>>>
>>> mpg("lots", "many")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in mpg
TypeError: unsupported operand type(s) for /: 'str' and 'str'
You could revise mpg() and use multiple except blocks to handle this situation, too:
Notice that the except keyword can also be used in conjunction with the as keyword.
This has the same effect as the other uses of as, giving the raised exception an alias so
you can work with it in the except block.
Even though it’s syntactically allowed, try not to use except statements as implicit
catchalls. It’s better practice to always explicitly catch something, even if it’s
just Exception:
try:
1 / 0
except: # Don't do this
pass
try:
1 / 0
except Exception: # This is better
pass
try:
1 / 0
except ZeroDivisionError: # This is best
pass
If you really do want to catch a broad range of exceptions, then specify the
parent Exception. This is more explicitly a catchall, and it won’t also catch exceptions you
probably don’t want to catch, like RuntimeError or KeyboardInterrupt.
The raise keyword raises an exception. If you find you need to raise an exception, then
you can use raise followed by the exception to be raised:
raise <exception>
You used raise previously, in the mpg() example. When you catch the TypeError, you re-
raise the exception after printing a message to the screen.
Python’s finally keyword is helpful for specifying code that should be run no matter
what happens in the try, except, or else blocks. To use finally, use it as part of
a try block and specify the statements that should be run no matter what:
try:
<statements>
finally:
<statements>
Using the example from before, it might be helpful to specify that, no matter what
happens, you want to know what arguments the function was called with. You could
modify mpg() to include a finally block that does just that:
>>>
>>> mpg(10, 1)
mpg(10, 1)
10.0
You’ve learned that the else keyword can be used with both the if keyword and loops
in Python, but it has one more use. It can be combined with the try and except Python
keywords. You can use else in this way only if you also use at least one except block:
try:
<statements>
except <exception>:
<statements>
else:
<statements>
In this context, the code in the else block is executed only if an exception was not raised
in the try block. In other words, if the try block executed all the code successfully, then
the else block code would be executed.
In the mpg() example, imagine you want to make sure that the mpg result is always
returned as a float no matter what number combination is passed in. One of the ways
you could do this is to use an else block. If the try block calculation of mpg is successful,
then you convert the result to a float in the else block before returning:
assert <expr>
Generally, assert statements will be used to make sure something that needs to be true
is. You shouldn’t rely on them, however, as they can be ignored depending on how your
Python program is executed.
The sections below introduce the two asynchronous keywords and their basic syntax,
but they won’t go into depth on asynchronous programming. To learn more about
asynchronous programming, check out Async IO in Python: A Complete
Walkthrough and Getting Started With Async Features in Python.
The async keyword is used with def to define an asynchronous function, or coroutine. The
syntax is just like defining a function, with the addition of async at the beginning:
Three Python keywords are used to work with variables. The del keyword is much more
commonly used than the global and nonlocal keywords. But it’s still helpful to know and
understand all three keywords so you can identify when and how to use them.
delis used in Python to unset a variable or name. You can use it on variable names, but
a more common use is to remove indexes from a list or dictionary. To unset a variable,
use del followed by the variable you want to unset:
del <variable>
Let’s assume you want to clean up a dictionary that you got from an API response by
throwing out keys you know you won’t use. You can do so with the del keyword:
>>>
>>> del response["headers"]
>>> del response["errors"]
This will remove the "headers" and "errors" keys from the dictionary response.
If you need to modify a variable that isn’t defined in a function but is defined in
the global scope, then you’ll need to use the global keyword. This works by specifying
in the function which variables need to be pulled into the function from the global
scope:
global <variable>
A basic example is incrementing a global variable with a function call. You can do that
with the global keyword:
>>>
>>> x = 0
>>> def inc():
... global x
... x += 1
...
>>> inc()
>>> x
1
>>> inc()
>>> x
2
This is generally not considered good practice, but it does have its uses. To learn much
more on the global keyword, check out Python Scope & the LEGB Rule: Resolving Names in
Your Code.
The nonlocal keyword is similar to global in that it allows you to modify variables from a
different scope. With global, the scope you’re pulling from is the global scope.
With nonlocal, the scope you’re pulling from is the parent scope. The syntax is similar
to global:
nonlocal <variable>
This keyword isn’t used very often, but it can be handy at times.