Chapter 4. Control Statements
Note
This chapter’s material is rich and intellectually challenging. Don’t give up if you start to feel lost (but do review it later to make sure you have absorbed it all). This chapter, together with the next, will complete our introduction to Python. To help you understand its contents, the chapter ends with some extended examples that reiterate the points made in its shorter examples. The rest of the book has a very different flavor.
Chapters 1 and 2 introduced simple statements:
Expressions, including function calls
Assignments
Augmented assignments
Various forms of import
Assertions
returnyield(to implement generators)pass
They also introduced the statements def, for defining functions, and with, to use with files.[20] These are compound statements because they require at least one indented statement after the
first line. This chapter introduces other compound statements. As with
def and with, the first line of every compound statement
must end with a colon and be followed by at least one statement indented
relative to it. Unlike def and with statements, though, the other compound
statements do not name anything. Rather, they determine the order in which
other statements are executed. That order is traditionally called the
control flow or flow of control,
and statements that affect it are called control statements.[21]
Some kinds of compound statements can or must have more than one clause. The first line of each clause of a compound statement—its header ...