Overview

8 Control flow

This chapter surveys Python’s core control-flow tools and how they work together to structure programs. It explains how Python evaluates conditions and truthiness, how blocks are delimited by indentation, and how decisions, loops, and comprehensions express common data-processing patterns concisely. Along the way, it emphasizes readable idioms, memory-aware iteration, and practical pitfalls to watch for, culminating in a small file-analysis program and a refactoring exercise.

Decision making starts with if/elif/else, including the use of pass for placeholder bodies, and extends to structural pattern matching with match/case, which can select by value, type, or multiple alternatives. Repetition is covered through while and for loops, both of which optionally support an else clause that runs only if the loop wasn’t terminated by break; continue skips to the next iteration. Iteration embraces any iterable, with techniques such as range (start/stop/step), tuple unpacking, enumerate for index-item pairs, and zip to walk multiple sequences in lockstep.

To express data transformations succinctly, the chapter introduces list, set, and dictionary comprehensions with optional filters, plus generator expressions that stream values without building full collections. It clarifies statement grouping, consistent indentation (prefer spaces over tabs), and safe line continuations, and it details Boolean logic: truthy/falsey values, comparison and membership operators, short-circuit behavior of and/or, and equality versus identity. The concluding example counts lines, words, and characters in a file and illustrates trade-offs among approaches (streaming versus reading all at once, and how splitting on newlines affects character counts), reinforcing the broader themes of clarity, correctness, and efficiency in control flow.

Summary

  • Python uses indentation to group blocks of code.
  • Python has loops using while and for, and conditionals using if-elif-else and a match statement that selects from multiple options.
  • Some common for loop patterns can be replaced by list, dictionary, or set comprehensions.
  • Generator expressions are similar to comprehensions, but usually use less memory
  • Python has the Boolean values True and False, which can be referenced by variables.
  • Most Python objects can also be evaluated as Booleans, with zero or empty valuwa being False and all other values being True.

FAQ

How do I write and use an if-elif-else statement in Python?

Use if for the first condition, any number of elif branches for alternatives, and an optional else for the “none of the above” case. Only the first true branch runs; the rest are skipped.

if x < 0:
    print("negative")
elif x == 0:
    print("zero")
else:
    print("positive")

Both elif and else are optional. If a block is required but you have nothing to do yet, use the no-op placeholder pass.

if condition:
    pass  # TODO: implement later
What is match/case (structural pattern matching) and how is it different from switch?

match/case (Python 3.10+) selects a branch by matching the structure or type of a value, not just equality. You can match literals, types, multiple options with |, and use _ as a catch-all.

match x:
    case "A":
        print("letter A")
    case str():
        print("some other string")
    case 1 | 2 | 3:
        print("small int")
    case int():
        print("some other int")
    case _:
        print("no match")

Be careful: patterns are powerful but can be subtle; test edge cases thoroughly.

How does a while loop work, and what does the optional else do?

A while loop runs its body while the condition is True. The optional else block runs only if the loop ends normally (i.e., not via break).

while condition:
    ...  # body
else:
    ...  # runs if no break occurred

break exits the loop immediately (skipping the else), and continue skips to the next iteration.

while True:
    s = input("> ")
    if s == "B":
        break      # else won't run
    if not s:
        continue   # skip rest of body
# else would go here if present
How is Python’s for loop different from C-style for loops?

Python’s for iterates over any iterable (lists, strings, range objects, generators, etc.), not over an index counter by default.

for ch in "spam":
    print(ch)

An optional else runs only if the loop wasn’t terminated by break.

How do I use range(), and what do start, stop, and step mean?

range(stop) yields 0..stop-1. range(start, stop) yields start..stop-1. range(start, stop, step) increments by step (use a negative step to count down). The stop value is excluded.

list(range(5))        # [0, 1, 2, 3, 4]
list(range(3, 7))     # [3, 4, 5, 6]
list(range(0, 10, 2)) # [0, 2, 4, 6, 8]
list(range(5, 0, -1)) # [5, 4, 3, 2, 1]

range returns a lightweight range object that generates numbers on demand (it doesn’t build a full list).

How can I iterate with indexes or combine multiple iterables?

Use enumerate() to get pairs of (index, item) and unpack them. Use zip() to pair items from multiple iterables (stops at the shortest).

for i, n in enumerate([10, 20, -5]):
    if n < 0:
        print("negative at", i)

for a, b in zip([1, 2, 3], ["a", "b"]):
    print(a, b)  # (1, "a"), (2, "b")

Tuple unpacking also works directly in for loops when iterating sequences of tuples.

What are list, set, and dict comprehensions, and when should I use them?

Comprehensions are concise “one-line loops” that build new collections, optionally filtering items.

# list comprehension
squares = [x*x for x in nums if x > 0]

# set comprehension
unique_pos = {x for x in nums if x > 0}

# dict comprehension
square_map = {x: x*x for x in nums}

They’re ideal when transforming/filtering data into a new collection in a clear, compact way.

What are generator expressions, and why use them instead of list comprehensions?

Generator expressions look like list comprehensions but use parentheses. They produce values on demand, saving memory for large data.

squares = (x*x for x in nums)  # generator
for v in squares:
    print(v)

Use them when you only need to iterate once and don’t need the whole list in memory.

How does indentation define blocks in Python, and what are common pitfalls?

Indentation delimits blocks; use consistent indentation within a block (PEP 8 recommends 4 spaces). Avoid mixing tabs and spaces (can cause IndentationError). You can place multiple simple statements on one line with semicolons, but it’s discouraged for readability.

Break long statements with a backslash or, preferably, inside (), [], or {} which allow implicit line continuation.

total = (a + b + c
         + d + e)

When splitting long strings with \, indentation becomes part of the string; instead, concatenate adjacent string literals.

How do Booleans, truthiness, and comparisons work in conditions?

In Boolean contexts, 0, 0.0, 0+0j, empty collections/strings, and None are False; most other values are True. Compare with <, <=, >, >=, ==, !=; use in/not in for membership and is/is not for identity.

if 0 < x < 10:  # chained comparison
    ...

and/or short-circuit and return one of their operands (not just True/False): and returns the first falsy value or the last value; or returns the first truthy value or the last value.

[] and 5    # []
[2] or [3] # [2]

# identity vs equality
a = [0]; b = [0]
a == b     # True (same contents)
a is b     # False (different objects)

pro $24.99 per month

  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose one free eBook per month to keep
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime

lite $19.99 per month

  • access to all Manning books, including MEAPs!

team

5, 10 or 20 seats+ for your team - learn more


choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • The Quick Python Book, Fourth Edition ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • The Quick Python Book, Fourth Edition ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • The Quick Python Book, Fourth Edition ebook for free