Recommended Video Course
Exploring Keywords in Python
Table of Contents
Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding:Exploring Keywords in Python
Python keywords are reserved words with specific functions and restrictions in the language. Currently, Python has thirty-five keywords and four soft keywords. These keywords are always available in Python, which means you don’t need to import them. Understanding how to use them correctly is fundamental for building Python programs.
By the end of this tutorial, you’ll understand that:
keyword.kwlist
from thekeyword
module.print
andexec
are keywords that have been deprecated and turned into functions in Python 3.In this article, you’ll find a basic introduction to all Python keywords and soft keywords along with other resources that will be helpful for learning more about each keyword.
Get Your Cheat Sheet:Click here to download a free cheat sheet that summarizes the main keywords in Python.
Take the Quiz: Test your knowledge with our interactive “Python Keywords: An Introduction” quiz. You’ll receive a score upon completion to help you track your learning progress:
Interactive Quiz
Python Keywords: An IntroductionIn this quiz, you'll test your understanding of Python keywords and soft keywords. These reserved words have specific functions and restrictions in Python, and understanding how to use them correctly is fundamental for building Python programs.
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’sbuilt-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 youcan’t do with Python keywords is assign something to them. If you try, then you’ll get aSyntaxError
. You won’t get aSyntaxError
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 outInvalid Syntax in Python: Common Reasons for SyntaxError.
There arethirty-five keywords in Python. Here’s a list of them, each linked to its relevant section in this tutorial:
False | await | else | import | pass |
None | break | except | in | raise |
True | class | finally | is | return |
and | continue | for | lambda | try |
as | def | from | nonlocal | while |
assert | del | global | not | with |
async | elif | if | or | yield |
Two keywords have additional uses beyond their initial use cases. Theelse
keyword is alsoused with loops andwithtry
andexcept
in addition to in conditional statements. Theas
keyword is most commonly used inimport
statements, but also usedwith thewith
keyword.
The list of Python keywords and soft keywords has changed over time. For example, theawait
andasync
keywords weren’t added until Python 3.7. Also, bothprint
andexec
were keywords in Python 2.7 but were turned into built-in functions in Python 3 and no longer appear in the keywords list.
As mentioned above, you’ll get an error if you try to assign something to a Python keyword. Soft keywords, on the other hand, aren’t that strict. They syntactically act as keywords only in certain conditions.
This new capability was made possible thanks to the introduction of thePEG parser in Python 3.9, which changed how the interpreter reads the source code.
Leveraging the PEG parser allowed for the introduction ofstructural pattern matching in Python. In order to use intuitive syntax, the authors pickedmatch
,case
, and_
for the pattern matching statements. Notably,match
andcase
are widely used for this purpose in many other programming languages.
To prevent conflicts with existing Python code that already usedmatch
,case
, and_
as variable or function names, Python developers decided to introduce the concept of soft keywords.
Currently, there are foursoft keywords in Python:
You can use the links above to jump to the soft keywords you’d like to read about, or you can continue reading for a guided tour.
True
,False
,None
There are three Python keywords that are used as values. These values aresingleton values that can be used over and over again and always reference the exact same object. You’ll most likely see and use these values a lot.
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:
Truthiness refers to theBoolean evaluation of a value. The truthiness of a value indicates whether the value istruthy orfalsy.
Truthy means any value that evaluates to true in the Boolean context. To determine if a value is truthy, pass it as the argument tobool()
. If it returnsTrue
, then the value is truthy. Examples of truthy values are non-empty strings, any numbers that aren’t0
, non-empty lists, and many more.
Falsy means any value that evaluates to false in the Boolean context. To determine if a value is falsy, pass it as the argument tobool()
. If it returnsFalse
, then the value is falsy. Examples of falsy values are""
,0
,[]
,{}
, andset()
.
For more on these terms and concepts, check outOperators and Expressions in Python.
True
andFalse
KeywordsTheTrue
keyword is used as the Boolean true value in Python code. The Python keywordFalse
is similar to theTrue
keyword, but with the opposite Boolean value of false. In other programming languages, you’ll see these keywords written in lowercase (true
andfalse
), but in Python they’re always capitalized.
The Python keywordsTrue
andFalse
can be assigned tovariables and compared directly:
>>>x=True>>>xisTrueTrue>>>y=False>>>yisFalseTrue
Most values in Python will evaluate toTrue
when passed tobool()
. There are only a few values in Python that will evaluate toFalse
when passed tobool()
:0
,""
,[]
, and{}
to name a few. Passing a value tobool()
indicates the value’s truthiness, or the equivalent Boolean value. You can compare a value’s truthiness toTrue
orFalse
by passing the value tobool()
:
>>>x="this is a truthy value">>>xisTrueFalse>>>bool(x)isTrueTrue>>>y=""# This is falsy>>>yisFalseFalse>>>bool(y)isFalseTrue
Notice that comparing a truthy value directly toTrue
orFalse
usingis
doesn’t work. You should compare a value toTrue
orFalse
directly only if you want to know whether it’sactually the valuesTrue
orFalse
.
When writing conditional statements that are based on the truthiness of a value, you shouldnot compare directly toTrue
orFalse
. You can rely on Python to do the truthiness check in conditionals for you:
>>>x="this is a truthy value">>>ifxisTrue:# Don't do this...print("x is True")...>>>ifx:# Do this...print("x is truthy")...x is truthy
In Python, you generally don’t need to convert values to be explicitlyTrue
orFalse
. Python will implicitly determine the truthiness of the value for you.
To learn more about theTrue
andFalse
keywords in Python, check out the tutorialPython Booleans: Use Truth Values in Your Code.
None
KeywordThe Python keywordNone
represents no value. In other programming languages,None
is represented asnull
,nil
,none
,undef
, orundefined
.
None
is also the default value returned by a function if it doesn’t have areturn
statement:
>>>deffunc():...print("hello")...>>>x=func()hello>>>print(x)None
To go more in depth on this very important and useful Python keyword, check outNull in Python: Understanding Python’s NoneType Object.
and
,or
,not
,in
,is
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:
Math Operator | Python Keyword | Other Languages |
---|---|---|
AND, ∧ | and | && |
OR, ∨ | or | || |
NOT, ¬ | not | ! |
CONTAINS, ∈ | in | |
IDENTITY | is | === |
Python code was designed for readability. That’s why many of the operators that use symbols in other programming languages are keywords in Python.
and
KeywordThe Python keywordand
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:
<expr1>and<expr2>
Note that the results of anand
statement will not necessarily beTrue
orFalse
. This is because of the quirky behavior ofand
. Rather than evaluating the operands to their Boolean values,and
simply returns<expr1>
if it is falsy or else it returns<expr2>
. The results of anand
statement could be passed tobool()
to get the explicitTrue
orFalse
value, or they could be used in a conditionalif
statement.
If you wanted to define an expression that did the same thing as anand
expression, but without using theand
keyword, then you could use the Python ternary operator:
leftifnotleftelseright
The above statement will produce the same result asleft and right
.
Becauseand
returns the first operand if it’s falsy and otherwise returns the last operand, you can also useand
in an assignment:
x=yandz
If y is falsy, then this would result inx
being assigned the value ofy
. Otherwise,x
would be assigned the value ofz
. However, this makes for confusing code. A more verbose and clear alternative would be:
x=yifnotyelsez
This code is longer, but it more clearly indicates what you’re trying to accomplish.
To learn more about theand
keyword, check out the tutorialUsing the “and” Boolean Operator in Python.
or
KeywordPython’sor
keyword is used to determine if at least one of the operands is truthy. Anor
statement returns the first operand if it is truthy and otherwise returns the second operand:
<expr1>or<expr2>
Just like theand
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 anor
expression without the use ofor
, then you could do so with a ternary expression:
leftifleftelseright
This expression will produce the same result asleft or right
. To take advantage of this behavior, you’ll also sometimes seeor
used in assignments. This is generally discouraged in favor of a more explicit assignment.
For a more in-depth look ator
, you can read abouthow to use the Pythonor
operator.
not
KeywordPython’snot
keyword is used to get the opposite Boolean value of a variable:
>>>val=""# Truthiness value is `False`>>>notvalTrue>>>val=5# Truthiness value is `True`>>>notvalFalse
Thenot
keyword is used in conditional statements or other Boolean expressions toflip the Boolean meaning or result. Unlikeand
andor
,not
will return an explicit Boolean value,True
orFalse
.
If you wanted to get the same behavior without usingnot
, then you could do so with the following ternary expression:
Falseif<expr>elseTrue
This statement would return the same result asnot <expr>
.
To learn more about thenot
keyword, check out the tutorialUsing the “not” Boolean Operator in Python.
in
KeywordPython’sin
keyword is a powerful containment check, ormembership operator. Given an element to find and a container or sequence to search,in
will returnTrue
orFalse
indicating whether the element was found in the container:
<element>in<container>
A good example of using thein
keyword is checking for a specific letter in a string:
>>>name="Chad">>>"c"innameFalse>>>"C"innameTrue
Thein
keyword works with all types of containers: lists, dicts, sets, strings, and anything else that defines__contains__()
or can be iterated over.
To learn more about thenot
keyword, check out the tutorialPython’s “in” and “not in” Operators: Check for Membership.
is
KeywordPython’sis
keyword is an identity check. This isdifferent from the==
operator, which checks for equality. Sometimes, two things can be considered equal but not be the exact same object in memory. Theis
keyword determines whether two objects are exactly the same object:
<obj1>is<obj2>
This will returnTrue
if<obj1>
is the exact same object in memory as<obj2>
, or else it will returnFalse
.
Most of the time, you’ll seeis
being used to check if an object isNone
. SinceNone
is a singleton, there’s only one instance ofNone
that can exist, so allNone
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 outPython ‘!=’ Is Not ‘is not’: Comparing Objects in Python. For a deeper dive into howis
works, check outOperators and Expressions in Python.
if
,elif
,else
Three Python keywords are used for control flow:if
,elif
, andelse
. 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.
if
KeywordTheif
keyword is used to start aconditional statement. Anif
statement allows you to write a block of code that gets executed only if the expression afterif
is truthy.
The syntax for anif
statement starts with the keywordif
at the beginning of the line, followed by a valid expression that will be evaluated for its truthiness value:
if<expr>:<statements>
Theif
statement is a crucial component of most programs. For more information about theif
statement, check outConditional Statements in Python.
Another use of theif
keyword is as part of Python’sternary operator:
<var>=<expr1>if<expr2>else<expr3>
This is a one-line version of theif...else
statement:
if<expr2>:<var>=<expr1>else:<var>=<expr3>
If your expressions are straightforward, 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 standardif
statement.
elif
KeywordTheelif
statement looks and functions like theif
statement, with two major differences:
elif
is only valid after anif
statement or anotherelif
.elif
statements as you need.In other programming languages,elif
appears as eitherelse if
, written as two separate words, orelseif
, written as one word:
if<expr1>:<statements>elif<expr2>:<statements>elif<expr3>:<statements>
Python doesn’t have aswitch
statement. One way to get the same functionality that other programming languages provide withswitch
statements is by usingif
andelif
. For other ways of reproducing theswitch
statement in Python, check outEmulating switch/case Statements in Python andStructural Pattern Matching in Python.
else
KeywordTheelse
statement, in conjunction with the Python keywordsif
andelif
, denotes a block of code that should be executed only if the other conditional blocks,if
andelif
, are all falsy:
if<expr>:<statements>else:<statements>
Notice that theelse
statement doesn’t take a conditional expression. Knowledge of theelif
andelse
keywords and their proper usage is critical for Python programmers. Together withif
, they make up some of the most frequently used components in any Python program.
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, 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.
for
KeywordThe most common loop in Python is thefor
loop. It’s constructed by combining the Python keywordsfor
andin
explained earlier. The basic syntax for afor
loop is as follows:
for<element>in<container>:<statements>
A common example is looping over the numbers one through five andprinting them to the screen:
>>>fornuminrange(1,6):...print(num)...12345
In many other programming languages, the syntax for afor
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, thefor
loop is like afor-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"]>>>forpersoninpeople:...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 a list of people’s names. Thefor
loop starts with thefor
keyword at the beginning of the line, followed by a variable that stores each list element, then thein
keyword, and finally the container, which in this case ispeople
.
Python’sfor
loop is another major ingredient in any Python program. To learn more aboutfor
loops, check outPython for Loops: The Pythonic Way.
while
KeywordPython’swhile
loop uses the keywordwhile
and works like awhile
loop in other programming languages. As long as the condition that follows thewhile
keyword is truthy, the block following thewhile
statement will continue to be executed over and over again:
while<expr>:<statements>
Note: For the infinite loop example below, be prepared to useCtrl+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 thewhile
keyword with an expression that’s always truthy:
>>>whileTrue:...print("working...")...
For more practical examples of infinite loops in action, check outSocket Programming in Python (Guide). To learn more aboutwhile
loops, check outPython while Loops: Repeating Tasks Conditionally.
break
KeywordIf you need to exit a loop early, then you can use thebreak
keyword. This keyword will work in bothfor
andwhile
loops:
for<element>in<container>:if<expr>:break
An example of using thebreak
keyword would be if you were summing the integers in a list of numbers and wanted to quit when the total went above a given value:
>>>nums=[1,2,3,4,5,6,7,8,9,10]>>>total_sum=0>>>fornuminnums:...total_sum+=num...iftotal_sum>10:...break...>>>total_sum15
Both the Python keywordsbreak
andcontinue
can be useful tools when working with loops. For a deeper discussion of their uses, check outPython “while” Loops (Indefinite Iteration). If you’d like to explore another use case for thebreak
keyword, then you can learnhow to emulate do-while loops in Python.
continue
KeywordPython also has acontinue
keyword for when you want to skip to the next loop iteration. Like in most other programming languages, thecontinue
keyword allows you to stop executing the current loop iteration and move on to the next iteration:
for<element>in<container>:if<expr>:continue
Thecontinue
keyword also works inwhile
loops. If thecontinue
keyword is reached in a loop, then the current iteration is stopped, and the next iteration of the loop is started.
else
Keyword Used With LoopsIn addition to using theelse
keyword with conditionalif
statements, you can also use it as part of a loop. When used with a loop, theelse
keyword specifies code that should be run if the loop exits normally, meaningbreak
was not called to exit the loop early.
The syntax for usingelse
with afor
loop looks like the following:
for<element>in<container>:<statements>else:<statements>
This looks very similar to usingelse
with anif
statement. Usingelse
with awhile
loop is similar:
while<expr>:<statements>else:<statements>
The Python standard documentation has a section onusingbreak
andelse
with afor
loop that you should really check out. It uses a great example to illustrate the usefulness of theelse
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 standardfor
loop with aflag variable:
>>>forninrange(2,10):...prime=True...forxinrange(2,n):...ifn%x==0:...prime=False...print(f"{n} is not prime")...break...ifprime:...print(f"{n} is prime!")...2 is prime!3 is prime!4 is not prime5 is prime!6 is not prime7 is prime!8 is not prime9 is not prime
You can use theprime
flag to indicate how the loop was exited. If it exited normally, then theprime
flag staysTrue
. If it exited withbreak
, then theprime
flag will be set toFalse
. Once outside the innerfor
loop, you can check the flag to determine ifprime
isTrue
and, if so, print that the number is prime.
Theelse
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:
>>>forninrange(2,10):...forxinrange(2,n):...ifn%x==0:...print(f"{n} is not prime")...break...else:...print(f"{n} is prime!")...2 is prime!3 is prime!4 is not prime5 is prime!6 is not prime7 is prime!8 is not prime9 is not prime
The only thing that you need to do to use theelse
block in this example is to remove theprime
flag and replace the finalif
statement with theelse
block. This ends up producing the same result as the example before, only with clearer code.
Sometimes using anelse
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
,class
,with
,as
,pass
,lambda
In order todefine functions and classes or usecontext managers, you’ll need to use one of the Python keywords in this section. They’re an essential part of the Python language, and understanding when to use them will help you become a better Python programmer.
def
KeywordPython’s keyworddef
is used to define a function or method of a class. This is equivalent tofunction
in JavaScript and PHP. The basic syntax for defining a function withdef
looks like this:
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 outDefining Your Own Python Function.
class
KeywordTo define a class in Python, you use theclass
keyword. The general syntax for defining a class withclass
is as follows:
classClassName(<extends>):<body>
Classes are powerful tools in object-oriented programming, and you should know about them and how to define them. To learn more, check outPython Classes: The Power of Object-Oriented Programming andObject-Oriented Programming (OOP) in Python.
with
KeywordContext 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 thewith
keyword:
with<contextmanager>as<var>:<statements>
Usingwith
gives you a way to define code to be executed within the context manager’sscope. The most basic example of this is when you’re working withfile I/O in Python.
If you wanted toopen a file, do something with that file, and then make sure that the file wasclosed correctly, then you would use a context manager. Consider this example in whichnames.txt
contains a list of names, one per line:
>>>withopen("names.txt")asinput_file:...fornameininput_file:...print(name.strip())...JimPamCecePhilip
The file I/O context manager provided byopen()
and initiated with thewith
keyword opens the file for reading, assigns the open file pointer toinput_file
, then executes whatever code you specify in thewith
block. Then, after the block is executed, the file pointer closes. Even if your code in thewith
block raises an exception, the file pointer would still close.
For a great example of usingwith
and context managers, check outPython Timer Functions: Three Ways to Monitor Your Code or dive deeper in the tutorialContext Managers and Python’s with Statement.
as
Keyword Used Withwith
If you want access to the results of the expression or context manager passed towith
, you’ll need to alias it usingas
. You may have also seenas
used to alias imports and exceptions, and this is no different. The alias is available in thewith
block:
with<expr>as<alias>:<statements>
Most of the time, you’ll see these two Python keywords,with
andas
, used together.
pass
KeywordSince Python doesn’t have block indicators to specify the end of a block, thepass
keyword is used to specify that the block is intentionally left blank. It’s the equivalent of ano-op, orno operation. Here are a few examples of usingpass
to specify that the block is blank:
defempty_function():passclassEmptyClass:passifTrue:pass
For more onpass
, check outThe pass Statement: How to Do Nothing in Python.
lambda
KeywordThelambda
keyword is used to define a function that doesn’t have a name and has only one expression, the results of which are returned. Functions defined withlambda
are referred to aslambda functions:
lambda<args>:<expression>
A basic example of alambda
function that computes the argument raised to the power of10
would look like this:
p10=lambdax:x**10
This is equivalent to defining a function withdef
:
defp10(x):returnx**10
One common use for alambda
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 ofsorted()
would sort the strings alphabetically. But withsorted()
, you can specify which key the list should be sorted on.
A lambda function provides a nice way to do so:
>>>ids=["id1","id2","id30","id3","id20","id10"]>>>sorted(ids)['id1', 'id10', 'id2', 'id20', 'id3', 'id30']>>>sorted(ids,key=lambdax:int(x[2:]))['id1', 'id2', 'id3', 'id10', 'id20', 'id30']
This example sorts the list based not on alphabetical order but on the numerical order of the last characters of the strings after converting them to integers. Withoutlambda
, you would have had to define a function, give it a name, and then pass it tosorted()
. Usinglambda
made this code cleaner.
For comparison, this is what the example above would look like without usinglambda
:
>>>defsort_by_int(x):...returnint(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 thelambda
example, but you need to define the function before using it.
For a lot more information aboutlambda
, check outHow to Use Python Lambda Functions.
return
,yield
There are two Python keywords used to specify what gets returned from functions or methods:return
andyield
. Understanding when and where to usereturn
is vital to becoming a better Python programmer. Theyield
keyword is a more advanced feature of Python, but it can be a useful tool to understand.
return
KeywordPython’sreturn
keyword is valid only as part of a function defined withdef
. When Python encounters this keyword, it will exit the function at that point and return the results of whatever comes after thereturn
keyword:
def<function_name>():return<expr>
When given no expression,return
will returnNone
by default:
>>>defreturn_none():...return...>>>r=return_none()>>>print(r)None
Most of the time, however, you want to return the results of an expression or a specific value:
>>>defplus_1(num):...returnnum+1...>>>plus_1(9)10>>>r=plus_1(9)>>>print(r)10
You can even use thereturn
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 followingrecursive solution to calculatingfactorial:
deffactorial(n):ifn==1:return1else:returnn*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 is1
, 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 thereturn
keyword, check outThe Python return Statement: Usage and Best Practices andDefining Your Own Python Function.
yield
KeywordPython’syield
keyword is kind of like thereturn
keyword in that it specifies what gets returned from a function. However, when a function has ayield
statement, what gets returned is agenerator. The generator can then be passed to Python’s built-innext()
to get the next value returned from the function.
When you call a function withyield
statements, Python executes the function until it reaches the firstyield
keyword and then returns a generator. These are known as generator functions:
def<function_name>():yield<expr>
The most straightforward example of this would be a generator function that returns the same set of values:
>>>deffamily():...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):...StopIteration
Once theStopIteration
exception is raised, the generator is done returning values. In order to go through the names again, you would need to callfamily()
again and get a new generator. Most of the time, a generator function will be called as part of afor
loop, which does thenext()
calls for you.
For much more on theyield
keyword and using generators and generator functions, check outHow to Use Generators and yield in Python andPython Generators 101.
import
,from
,as
Some tools, such as Python keywords and built-in functions, are always available in your program. However, for other tools that aren’t built in, you’ll need to import them. Python’s standard library offers many useful modules that are only an import away. Additionally,PyPI provides a vast collection of third-party libraries and tools 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. For more information about these keywords, check outPython Modules and Packages – An Introduction andPython import: Advanced Techniques and Tips.
import
KeywordPython’simport
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 theCounter
class from thecollections
module in the standard library, then you can use the following code:
>>>importcollections>>>collections.Counter()Counter()
Importingcollections
in this way makes the wholecollections
module, including theCounter
class, available to your program. By using the module name, you have access to all the tools available in that module. To get access toCounter
, you reference it from the module:collections.Counter
.
from
KeywordThefrom
keyword is used together withimport
to import something specific from a module:
from<module>import<thing>
This will import whatever<thing>
is inside<module>
to be used inside your program. These two Python keywords,from
andimport
, are used together.
If you want to useCounter
from thecollections
module in the standard library, then you can import it specifically:
>>>fromcollectionsimportCounter>>>Counter()Counter()
ImportingCounter
like this makes theCounter
class available, but nothing else from thecollections
module is available.Counter
is now available without you having to reference it from thecollections
module.
as
KeywordTheas
keyword is used toalias an imported module or tool. It’s used together with the Python keywordsimport
andfrom
to change the name of the thing being imported:
import<module>as<alias>from<module>import<thing>as<alias>
For modules that have really long names or a commonly used import alias,as
can be helpful in creating the alias.
If you want to import theCounter
class from the collections module but name it something different, you can alias it by usingas
:
>>>fromcollectionsimportCounterasC>>>C()Counter()
NowCounter
is available to be used in your program, but it’s referenced byC
instead. A more common use ofas
import aliases is withNumPy orpandas packages. These are commonly imported with standard aliases:
importnumpyasnpimportpandasaspd
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.
try
,except
,raise
,finally
,else
,assert
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 outPython Exceptions: An Introduction.
try
KeywordAny exception-handling block begins with Python’stry
keyword. This is the same in most other programming languages that have exception handling.
The code inside thetry
block is code that might raise an exception. Several other Python keywords are associated withtry
and are used to define what should be done if different exceptions are raised. These keywords areexcept
,else
, andfinally
:
try:<statements><except|else|finally>:<statements>
Atry
block isn’t valid unless it has at least one of the other Python keywords used for exception handling as part of the overalltry
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:
defmiles_per_gallon(miles,gallons):returnmiles/gallons
The first problem you might see is that your code could raise aZeroDivisionError
if thegallons
parameter is passed in as0
. Thetry
keyword allows you to modify the code above to handle that situation appropriately:
defmiles_per_gallon(miles,gallons):try:mpg=miles/gallonsexceptZeroDivisionError:mpg=Nonereturnmpg
Now ifgallons = 0
, thenmiles_per_gallon()
won’t raise an exception and will returnNone
instead. This might be better, or you might decide that you want to raise a different type of exception or handle this situation differently. You’ll see an expanded version of this example below to illustrate the other keywords used for exception handling.
except
KeywordPython’sexcept
keyword is used withtry
to define what to do when specific exceptions are raised. You can have one or moreexcept
blocks with a singletry
. The basic usage looks like this:
try:<statements>except<exception>:<statements>
Taking themiles_per_gallon()
example from before, you could also do something specific in the event that someone passes types that won’t work with the/
operator. Having definedmiles_per_gallon()
in a previous example, now try to call it with strings instead of numbers:
>>>miles_per_gallon("lots","many")Traceback (most recent call last):...TypeError:unsupported operand type(s) for /: 'str' and 'str'
You could revisemiles_per_gallon()
and use multipleexcept
blocks to handle this situation, too:
defmiles_per_gallon(miles,gallons):try:mpg=miles/gallonsexceptZeroDivisionError:mpg=NoneexceptTypeErrorasexc:print("you need to provide numbers")raiseexcreturnmpg
Here, you modifymiles_per_gallon()
to raise theTypeError
exception only after you’ve printed a helpful reminder to the screen.
Note: Since Python 3.11, you can also useexcept*
to filter errors in exception groups. SeePython 3.11 Preview: Task and Exception Groups to learn more.
Notice that theexcept
keyword can also be used in conjunction with theas
keyword. This has the same effect as the other uses ofas
, giving the raised exception an alias so you can work with it in theexcept
block.
Even though it’s syntactically allowed, try not to useexcept
statements as implicit catchalls. It’s better practice to always explicitly catchsomething, even if it’s justException
:
try:1/0except:# Never do thispasstry:1/0exceptException:# This is betterpasstry:1/0exceptZeroDivisionError:# This is bestpass
If you really do want to catch a broad range of exceptions, then specify the parentException
. This is more explicitly a catchall, and it won’t also catch exceptions you probably don’t want to catch, likeRuntimeError
orKeyboardInterrupt
.
raise
KeywordTheraise
keyword raises an exception. If you find you need to raise an exception, then you can useraise
followed by the exception to be raised:
raise<exception>
You usedraise
previously in themiles_per_gallon()
example. When you catch theTypeError
, you re-raise the exception after printing a message to the screen.
For more onraise
, check outPython’sraise
: Effectively Raising Exceptions in Your Code.
finally
KeywordPython’sfinally
keyword is helpful for specifying code that should be run no matter what happens in thetry
,except
, orelse
blocks. To usefinally
, use it as part of atry
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 modifymiles_per_gallon()
to include afinally
block that does just that:
defmiles_per_gallon(miles,gallons):try:mpg=miles/gallonsexceptZeroDivisionError:mpg=NoneexceptTypeErrorasexc:print("you need to provide numbers")raiseexcfinally:print(f"miles_per_gallon({miles},{gallons})")returnmpg
Now, no matter howmiles_per_gallon()
is called or what the result is, you print the arguments supplied by the user:
>>>miles_per_gallon(10,1)miles_per_gallon(10, 1)10.0>>>miles_per_gallon("lots","many")you need to provide numbersmiles_per_gallon(lots, many)Traceback (most recent call last):...TypeError:unsupported operand type(s) for /: 'str' and 'str'
As you can see, thefinally
keyword can be a very useful part of your exception-handling code.
else
Keyword Used Withtry
andexcept
You’ve learned that theelse
keyword can be used with both theif
keyword and loops in Python, but it has one more use. It can be combined with thetry
andexcept
Python keywords. You can useelse
in this way only if you also use at least oneexcept
block:
try:<statements>except<exception>:<statements>else:<statements>
In this context, the code in theelse
block is executed only ifno exception is raised in thetry
block. In other words, if thetry
block executes all the code successfully, then theelse
block code will be executed.
In themiles_per_gallon()
example, imagine you want to make sure that thempg
result is always returned as afloat
no matter what number combination is passed in. One of the ways you could do this is to use anelse
block. If thetry
block calculation ofmpg
is successful, then you convert the result to afloat
in theelse
block before returning:
defmiles_per_gallon(miles,gallons):try:mpg=miles/gallonsexceptZeroDivisionError:mpg=NoneexceptTypeErrorasexc:print("you need to provide numbers")raiseexcelse:mpg=float(mpg)ifmpgisnotNoneelsempgfinally:print(f"miles_per_gallon({miles},{gallons})")returnmpg
Now the results of a call tomiles_per_gallon()
, if successful, will always be afloat
.
For more on using theelse
block as part of atry
andexcept
block, check outPython Exceptions: An Introduction.
assert
KeywordTheassert
keyword in Python is used to specify anassert
statement, or an assertion about an expression. Anassert
statement will result in a no-op if the expression (<expr>
) is truthy, and it will raise anAssertionError
if the expression is falsy. To define an assertion, useassert
followed by an expression:
assert<expr>
Generally, you useassert
statements to make sure something that needs to be true is. You shouldn’t rely on them for runtime logic, however, as they can be ignored depending on how your Python program is executed.
To learn more about theassert
keyword, check out the tutorialPython’s assert: Debug and Test Your Code Like a Pro.
async
,await
Asynchronous programming is a complex topic. There are two Python keywords defined to help make asynchronous code more readable and cleaner:async
andawait
.
The sections below introduce the two asynchronous keywords and their basic syntax, but don’t cover asynchronous programming in depth. To learn more about asynchronous programming, check outAsync IO in Python: A Complete Walkthrough andGetting Started With Async Features in Python.
async
KeywordTheasync
keyword is used withdef
to define an asynchronous function, orcoroutine. The syntax is just like defining a function, with the addition ofasync
at the beginning:
asyncdef<function>(<params>):<statements>
You can make a function asynchronous by adding theasync
keyword before the function’s regular definition.
await
KeywordPython’sawait
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. To use it, placeawait
before a call to anyasync
function:
await<someasyncfunctioncall><var>=await<someasyncfunctioncall>
When usingawait
, you can either call the asynchronous function and ignore the results, or you can store the results in a variable when the function eventually returns.
del
,global
,nonlocal
Three Python keywords are used to work with variables. Thedel
keyword is more commonly used than theglobal
andnonlocal
keywords. But it’s still helpful to know and understand all three keywords so you can identify when and how to use them.
del
KeywordThedel
keyword is used in Python to unset a variable or name. While you can use it on variable names, it’s more commonly used to remove indexes from alist ordictionary. To unset a variable, usedel
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 thedel
keyword:
>>>delresponse["headers"]>>>delresponse["errors"]
This will remove the"headers"
and"errors"
keys from the dictionaryresponse
.
To learn more about thedel
keyword, check out the tutorialPython’s del: Remove References From Scopes and Containers.
global
KeywordIf you need to modify a variable that isn’t defined in a function but is defined in theglobal scope, then you’ll need to use theglobal
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 aglobal variable with a function call. You can do that with theglobal
keyword:
>>>x=0>>>definc():...globalx...x+=1...>>>inc()>>>x1>>>inc()>>>x2
This is generally not considered good practice, but it does have its uses. To learn much more about theglobal
keyword, check outPython Scope & the LEGB Rule: Resolving Names in Your Code.
nonlocal
KeywordThenonlocal
keyword is similar toglobal
in that it allows you to modify variables from a different scope. Withglobal
, the scope you’re pulling from is the global scope. Withnonlocal
, the scope you’re pulling from is theparent scope. The syntax is similar toglobal
:
nonlocal<variable>
This keyword isn’t used very often, but it can be handy at times. For a deeper understanding of scoping and thenonlocal
keyword, refer toPython Scope & the LEGB Rule: Resolving Names in Your Code.
As mentioned before,soft keywords are contextual. They act as keywords only in specific contexts. That means you may encounter these names in code where they act as variable or function names.
When soft keywords are used in their intended context, they act just like any other keyword.
match
,case
, and_
Soft KeywordsThematch
,case
, and_
(underscore) soft keywords are used forstructural pattern matching:
defsum_ingredients(ingredient_counts):matchingredient_counts:case[]:return0case[first,*rest]:returnfirst+sum_ingredients(rest)case_:raiseValueError(f"Can only sum lists.")
You start with amatch
statement that specifies what you want to match. Then, one or severalcase
statements follow. Each case describes one pattern.
The indented block beneath it says what should happen if there’s a match. You can use the_
as a wildcard pattern that matches anything without binding it to a name.
type
Soft KeywordWhen you see the word “type”, you might think of the built-intype()
function. However, since Python 3.12,type
is also a soft keyword.
When you usetype
as atype alias defintinion,type
becomes a keyword:
importrandomtypeCardDeck=list[tuple[str,int]]defshuffle(deck:CardDeck)->CardDeck:returnrandom.sample(deck,k=len(deck))
With atype
statement like this, you can define an alias to be more descriptive about your data structures.
The list of Python keywords has changed over time. For example, theawait
andasync
keywords weren’t added until Python 3.7. Also, bothprint
andexec
were keywords in Python 2.7 but were turned into built-in functions in Python 3 and no longer appear in the list of keywords.
Soft keywords were introduced in Python 3.10. Back then, there was onlycase
,match
, and_
. Thetype
soft keyword was added in Python 3.12.
In the following sections, you’ll learn several ways to identify which words are keywords, and which soft keywords are available in the Python version you’re using.
There are a lot ofgood 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 thePython REPL, there are a number of ways you can identify valid Python keywords and learn more about them.
You can get a list of available keywords by usinghelp()
:
>>>help("keywords")Here is a list of the Python keywords. Enter any keyword to get more help.False class from orNone continue global passTrue def if raiseand del import returnas elif in tryassert else is whileasync except lambda withawait finally nonlocal yieldbreak for not
Next, as indicated in the output above, you can usehelp()
again by passing in the specific keyword that you need more information about. You can do this, for example, with thepass
keyword:
>>>help("pass")The "pass" statement******************** pass_stmt ::= "pass""pass" is a null operation — when it is executed, nothing happens. Itis useful as a placeholder when a statement is required syntactically,but no code needs to be executed, for example: def f(arg): pass # a function that does nothing (yet) class C: pass # a class with no methods (yet)
Python also provides akeyword
module for working with Python keywords in a programmatic way. Thekeyword
module has four helpful members for dealing with keywords:
kwlist
provides a list of all the Python keywords for the version of Python you’re running.iskeyword()
provides a handy way to determine if a string is also a keyword.softkwlist
provides a list of all soft keywords in Python for the version of Python you’re running.issoftkeyword()
allows you to determine if a string is also a soft 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, usekeyword.kwlist
:
>>>importkeyword>>>keyword.kwlist['False', 'None', 'True', 'and', 'as', 'assert', 'async', ...>>>len(keyword.kwlist)35>>>keyword.iskeyword("type")False>>>keyword.issoftkeyword("type")True>>>keyword.softkwlist['_', 'case', 'match', 'type']
If you need to know more about keywords or work with them in a programmatic way, then you can use this documentation and tooling that Python provides for you.
SyntaxError
Finally, another indicator that a word you’re using is actually a keyword is if you get aSyntaxError
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’reusing a keyword incorrectly.
Sometimes a Python keyword becomes a built-in function. That was the case with bothprint
andexec
. These used to be Python keywords in version 2.7, but they’ve since been changed to built-in functions.
print
KeywordWhenprint
was a keyword, the syntax to print something to the screen looked like this:
print"Hello, World"
Notice that it looks like a lot of the other keyword statements, with the keyword followed by the arguments.
Nowprint
is no longer a keyword, and printing is accomplished with the built-inprint()
. To print something to the screen, you now use the following syntax:
print("Hello, World")
For more on printing, check outYour Guide to the Python print() Function.
exec
KeywordIn Python 2.7, theexec
keyword took Python code as a string and executed it. This was done with the following syntax:
exec"<statements>"
You can get the same behavior in Python 3+, only with the built-inexec()
. For example, if you wanted to execute"x = 12 * 7"
in your Python code, then you could do the following:
>>>exec("x = 12 * 7")>>>x==84True
For more onexec()
and its uses, check outHow to Run Your Python Scripts and Code andPython’s exec(): Execute Dynamically Generated Code.
Python keywords are the fundamental building blocks of any Python program. Understanding their proper use is key to improving your skills so you can write more efficient and readable code.
In this tutorial, you’ve learned:
keyword.kwlist
from thekeyword
module.print
andexec
are keywords that have been deprecated and turned into functions in Python 3.If you understand most of these keywords and feel comfortable using them, then you might be interested in learning more aboutPython’s grammar and how thestatements that use these keywords are specified and constructed.
Get Your Cheat Sheet:Click here to download a free cheat sheet that summarizes the main keywords in Python.
Now that you have some experience with Python keywords in Python, you can use the questions and answers below to check your understanding and recap what you’ve learned.
These FAQs are related to the most important concepts you’ve covered in this tutorial. Click theShow/Hide toggle beside each question to reveal the answer.
Python has thirty-five keywords and four soft keywords.
You can use thekeyword
module in Python and callkeyword.kwlist
to get a list of all keywords.
Soft keywords in Python act as keywords only in certain contexts and can otherwise be used as variable or function names.
You can get more information about a keyword by using thehelp()
function in the Python REPL, and passing in the keyword you want to learn about as a string.
Theprint
andexec
keywords were deprecated and are now built-in functions in Python 3+.
Take the Quiz: Test your knowledge with our interactive “Python Keywords: An Introduction” quiz. You’ll receive a score upon completion to help you track your learning progress:
Interactive Quiz
Python Keywords: An IntroductionIn this quiz, you'll test your understanding of Python keywords and soft keywords. These reserved words have specific functions and restrictions in Python, and understanding how to use them correctly is fundamental for building Python programs.
Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding:Exploring Keywords in Python
🐍 Python Tricks 💌
Get a short & sweetPython Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.
AboutChad Hansen
Chad is an avid Pythonista and does web development with Django fulltime. Chad lives in Utah with his wife and six kids.
» More about ChadMasterReal-World Python Skills With Unlimited Access to Real Python
Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:
MasterReal-World Python Skills
With Unlimited Access to Real Python
Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:
What Do You Think?
What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.
Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students.Get tips for asking good questions andget answers to common questions in our support portal.
Keep Learning
Recommended Video Course:Exploring Keywords in Python
Related Tutorials:
Already have an account?Sign-In
Almost there! Complete this form and click the button below to gain instant access:
Python Keywords: An Introduction (Cheat Sheet)