Chapter 8. Control flow
This chapter covers
- Repeating code with a while loop
- Making decisions: the if-elif-else statement
- 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.
You’ve come across the basic while loop several times already. The full while loop looks like this:
condition is a Boolean expression—that is, one that evaluates to a True or False value. As long as it’s True, the body is executed repeatedly. When the condition evaluates to False, the while loop executes the post-code section and then terminates. If the condition starts out by being False, the body won’t be executed at all—just the post-code section. The body and post-code are each sequences of one or more Python statements that are separated by newlines and are at the same level of indentation. The Python interpreter uses this level to delimit them. No other delimiters, such as braces or brackets, are necessary.
Note that the else part of the while loop is optional and not often used. That’s because as long as there’s no break in the body, this loop
and this loop