00:00 In the last lesson, you learned what keywords are. In this lesson, you will use keywords. In order to do so, you will categorize them into more chewable parts. Let’s get started.
00:13 So far, we have grouped the keywords into two main categories: normal keywords and soft keywords. To grasp them better and have a closer look at them in this lesson, let’s categorize them even more.
00:29 In the upcoming slides, we’ll go through every category one by one, and I will explain the keywords with small examples. But before we move along, make sure to grab your cheat sheet.
00:41 You can find it in the supporting materials below, so you can print it out and have it on your side while I go through every category one by one.
00:52 I just wanted to say pause any time you want to have a closer look at the examples, so if I’m going too fast, just pause and continue when you’re ready.
01:05 All right. First up, there are the value keywords. There are three Python keywords that are used as values. These values are singleton values that can be used over and over again and always reference the exact same object.
True keyword is used as the Boolean true value in Python code. The Python keyboard
False is similar to the
True keyword but the opposite, false. The Python keyword
None represents no value.
None is also the default value returned by a function if it doesn’t have a
return statement. You will come to this a bit later in a later example.
else are used for control flow in your code. These keywords allow you to use conditional logic and execute code given certain conditions.
if keyword is used to start a conditional statement. An
if statement allows you to write a block of code that gets executed only if the expression after
if is considered to be true.
elif statement looks and functions like the
if statement, with two major differences. Using
elif is only valid after an
if statement or another
You can use as many
elif statements as you need. The
else statement in conjunction with the Python keyword
elif denotes a block of code that should be executed only if the other conditional blocks,
elif, are all considered to be false.
So while you may see an
if statement alone, you will never see an
else statement alone.
Python code was designed for readability. That’s why many of the operators that use symbols in other programming languages are actual words in Python. We can group them as operator keywords. The Python keyword
and is used to determine if both the left and the right operands are considered true.
or keyword is used to determine if at least one of the operands is considered to be true. The
not keyword is used to get the opposite Boolean value of a variable.
in keyword is a so-called containment check. It will return
False, indicating whether the element was found in the container or not. Containers can be anything that can be iterated over—lists, dictionaries, sets, strings, and actually anything else that defines a
is keyword is an identity check. Sometimes two things can be considered equal, but they are not the same object in memory. The
is keyword determines whether two objects are exactly the same object in memory. A common use case for
is is checking a variable against
There are five iteration keywords in Python:
The example on the right shows a number guessing game. And the first keyword here is
while. As long as the condition that follows the
while keyword is considered true, the block following the
while statement will continue to be executed over and over again,
unless the user enters the actual secret number. Then this
while loop breaks with the
If the guess of the user is not numeric, then the
continue keyword jumps to the next iteration, and the user is asked to enter a number again.
else statement here—you already met them as conditional statements—but there is another
else down there.
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 keywords specifies code that should be run if the loop exits normally, meaning
break was not called to exit the loop early.
Let’s move on to structure keywords. Python’s keyword
def is used to define a function or method of a class. To define a class in Python, you use the
class keyword. 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. Using
with gives you a way to define code to be executed within the context manager’s scope.
A common use case is when you’re working with files in Python. Context managers are really helpful structure in Python. Each context manager executes specific code before and after the statements you specify, like opening and closing a file. To use one, you use the
If you want access to the results of the expression or context manager passed to
with, you’ll need to alias it using
The last structure keyword is
lambda keyword is used to define a function that doesn’t have a name and has only one statement of which the results are returned.
One common use for
lambda functions is specifying a different behavior for another function. For example, imagine you want to just sort of list of strings by their integer value.
The default behavior of the
sorted() function would sort the strings alphabetically. 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. Without
lambda, you would have to have to define a function, give it a name, and then pass it to the
There are two Python keywords that are used to specify what gets returned from functions or methods:
return keyword is valid only as part of a function defined with
When Python encounters this keyword, it will exit the function at that point and return the results of whatever comes after the
When given no expression,
return will return
None by default.
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.
In other words, every time you use
yield in a function, you automatically make this function into a generator function.
There are three importing keywords in Python:
import keyword is used to import a module for use in your Python program. The
from keyword is used together with
import to import something specific from a module. The
as keyword is used to alias an imported module or tool.
08:27 One of the aspects of any Python program is raising and catching 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.
assert keyword in Python is used to specify an
assert statement or an assertion about an expression. Generally,
assert statements will be used to make sure something that needs to be true is true. You shouldn’t rely on them, however, as they can be ignored, depending on how your Python program is executed.
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
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
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. And there it is again, the
You’ve learned that the
else keyword can be used with both the
if keyword and loops and Python, but it has one more use. It can be combined with the
except Python keywords.
You can use
else in this way only if you also use at least one
except block. 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. Python’s
finally keyword is helpful for specifying code that should be run no matter what happens in the
raise keyword raises an exception, as the name suggests.
There are two Python keywords defined to help make asynchronous code more readable and cleaner:
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.
await keyword is used in asynchronous functions to specify a point in the function where control is given back to the event loop for other functions to run.
You can use it by placing the
await keyword in front of a call to any async function.
nonlocal are keywords that are used to work with the scope of variables. 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
This works by specifying in the function which variables need to be pulled into the function from the global scope. 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.
del is 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.
And finally, the soft keywords again. So while the other groups—I have to admit—are basically made up to group the keywords for you, the soft keywords are an official category, and you already met them before in a lesson. Also, as you learned before, their use is with pattern matching, and this is possible while still preserving compatibility with existing code that uses
_ (underscore) as identifier names.
case construct is new in Python 3.10. And this is how you perform structural pattern matching. You start with a
match statement that specifies what you want to match. One or several
case statements follow
12:52 Each case describes one pattern, and the indented block beneath it says what should happen if there is a match. You can use the underscore as a wild-card pattern that matches anything without binding it to a name.
13:09 So with that were quite a few keywords. I admit even with a cheat sheet, it can be quite hard to remember them all. But luckily there are ways of identifying keywords, and you will learn about those ways in the next lesson.
Become a Member to join the conversation.