
8 Control flow
This chapter covers
- Making decisions: the if-elif-else statement
- Structural pattern matching
- Repeating code with a while loop
- Iterating over a list with a for loop
- Using list and dictionary comprehensions
- Delimiting statements and blocks with indentation
- Evaluating Boolean values and expressions
Python provides a complete set of control flow elements, with loops and conditionals. This chapter examines each element in detail.
8.1 The if-elif-else statement
One of the most important control flow features in most programming languages is the one for branching—that is, for making decisions on whether or not to execute or skip a piece of code based on some conditional. In Python, as in many languages, there are three parts to this: an if section, optionally one or more elif sections that are only checked if the if condition (and any previous elifs) is false, and a final optional else section that is only executed if neither the if or elif sections were executed.
The general form of the if-elif-else construct in Python is
if condition1: body1 elif condition2: body2 elif condition3: body3 . . . elif condition(n-1): body(n-1) else: body(n)