The Quick Python Book, Fourth Edition cover
welcome to this free extract from
an online version of the Manning book.
to read more
or

8 Control flow

 

This chapter covers

  • Making decisions: the if-elif-else statement
  • Structural pattern matching
  • Repeating code with a while loop
  • 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 if-elif-else statement

One of the most important control flow features in most programming languages is the one for branching—that is, for making decisions on whether or not to execute or skip a piece of code based on some conditional. In Python, as in many languages, there are three parts to this: an if section, optionally one or more elif sections that are only checked if the if condition (and any previous elifs) is false, and a final optional else section that is only executed if neither the if or elif sections were executed.

The general form of the if-elif-else construct in Python is

if condition1:
   body1
elif condition2:
   body2
elif condition3:
   body3
.
.
.
elif condition(n-1):
   body(n-1)
else:
   body(n)

8.2 Structural pattern matching with match

8.3 The while loop

8.4 The for loop

8.4.1 The range function

8.5 Controlling range with starting and stepping values

8.6 The for loop and tuple unpacking

8.7 The enumerate function

8.8 The zip function

8.9 List, set, and dictionary comprehensions

8.9.1 Generator expressions

8.10 Statements, blocks, and indentation

8.11 Boolean values and expressions

8.11.1 Most Python objects can be used as Booleans

8.11.2 Comparison and Boolean operators

8.12 Writing a simple program to analyze a text file

8.13 Refactoring word_count