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 ...

Get The Quick Python Book, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.