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.

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

Get The Quick Python Book, Second 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.