Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set your subtitle preferences in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please refer to our video player troubleshooting guide for assistance.

Categorizing Keywords

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.

01:21 The 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.

01:36 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.

01:47 if, elif, and else are used for control flow in your code. These keywords allow you to use conditional logic and execute code given certain conditions.

01:57 The 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.

02:10 The elif statement looks and functions like the if statement, with two major differences. Using elif is only valid after an if statement or another elif.

02:22 You can use as many elif statements as you need. The else statement in conjunction with the Python keyword if and elif denotes a block of code that should be executed only if the other conditional blocks, if and elif, are all considered to be false.

02:39 So while you may see an if statement alone, you will never see an elif or else statement alone.

02:48 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.

03:09 Python’s 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.

03:22 Python’s in keyword is a so-called containment check. It will return True or 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 .__contains__() method.

03:43 Python’s 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 True, False, or None.

04:06 There are five iteration keywords in Python: for, while, break, continue, and else.

04:14 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,

04:33 unless the user enters the actual secret number. Then this while loop breaks with the break keyword.

04:43 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.

04:55 The if, elif, and else statement here—you already met them as conditional statements—but there is another else down there.

05:04 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.

05:24 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.

05:54 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 with keyword.

06:12 If you want access to the results of the expression or context manager passed to with, you’ll need to alias it using as.

06:22 The last structure keyword is lambda. The 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.

06:34 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.

06:45 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 sorted() function.

07:11 There are two Python keywords that are used to specify what gets returned from functions or methods: return and yield. Python’s return keyword is valid only as part of a function defined with def.

07:26 When Python encounters this keyword, it will exit the function at that point and return the results of whatever comes after the return keyword.

07:36 When given no expression, return will return None by default.

07:41 The 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.

07:54 In other words, every time you use yield in a function, you automatically make this function into a generator function.

08:04 There are three importing keywords in Python: import, from, and as. Python’s 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.

08:42 The 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.

09:02 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. 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.

09:30 The 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 else keyword.

09:44 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 try and except Python keywords.

09:55 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 tryexcept or else blocks.

10:26 The raise keyword raises an exception, as the name suggests.

10:33 There are two Python keywords defined to help make asynchronous code more readable and cleaner: async and await. 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.

10:55 Python’s 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.

11:06 You can use it by placing the await keyword in front of a call to any async function.

11:14 The keywords del, global, and 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 global keyword.

11:32 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.

11:55 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.

12:07 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 match, case, and _ (underscore) as identifier names.

12:38 The matchcase 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 match.

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.