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 in detail.
You’ve come across the basic while loop several times already. The full while loop looks like this:
condition is an expression that evaluates to a true or false value. As long as it’s True, the body will be executed repeatedly. If it evaluates to False, the while loop will execute the post-code section and then terminate. 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 is no break in the body, this loop
and this loop