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.

8.1. The while loop

You’ve come across the basic while loop several times already. The full while loop looks like this:

while condition:
    body
else:
    post-code

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

while condition:
    body
else:
    post-code

and this loop

while condition:
    body
post-code

8.2. The if-elif-else statement

8.3. The for loop

8.4. List and dictionary comprehensions

8.5. Statements, blocks, and indentation

8.6. Boolean values and expressions

8.7. Writing a simple program to analyze a text file

Summary

sitemap