Chapter 8: Control flow
Introduces the chapter’s coverage of Python control flow, including conditionals, loops, comprehensions, indentation, and Boolean expressions.
After this chapter you will be able to
- Conditional branch selection. Trace how Python checks an if condition, then any elif conditions in order, and executes the body for the first true condition or the optional else body.
- Value and type matching. Explain how Python's match-case differs from a simple value-based switch: it can select among cases by matching equal values or types.
- Case alternatives and fallback. Describe the kinds of case tests shown here, how `|` combines alternatives, and what happens with an optional `_` case or when no case matches.
- While condition and loop body. Explain when a while loop executes its body, when it stops, and how indentation identifies its blocks.
- Optional while else block. Explain when a while loop’s optional else block runs and why it can be useful when the body contains a break.
- Break and continue effects. Distinguish what break and continue do when executed in a while loop’s body.
- Iteration over iterable values. Explain that a Python for loop takes successive values from an iterable rather than traditionally incrementing and testing a variable, and describe how its body runs once for each value.
- For loop control statements. Distinguish what break and continue do in a for loop, and explain when the optional else block does not run.
- List indices with range. Explain how range and len work together to supply a for loop with the indices of a list, such as when finding the positions of negative values.
- Range bounds and step values. Explain how range uses a starting value, an excluded ending value, and an optional step, including why a descending range needs a negative step.
- Tuple unpacking in for loops. Explain how a for loop can unpack each two-element tuple into two variables, and why this makes the loop cleaner.
- Indexed iteration with enumerate. Explain how enumerate and tuple unpacking let a loop access both a list item and its index, and why this can be clearer than using range.
- Pairing iterables with zip. Explain that zip combines corresponding elements from two or more iterables into tuples and stops when the shortest iterable ends.
- Comprehensions as loop shortcuts. Explain how a comprehension replaces a common for-loop pattern that processes items to create a new collection, optionally selecting which items to include.
- Comprehension result types. Distinguish list, set, and dictionary comprehensions by the collections they create and the expressions they require.
- Generator expression behavior and benefit. Explain how a generator expression differs from a list comprehension in syntax and result, and why it can use less memory for large sequences.
- Indented blocks and nested statements. Explain how indentation marks the body of a compound statement and how putting a compound statement inside a block creates a nested block.
- Indentation consistency and errors. Describe why incorrectly aligned statements raise exceptions and how consistent indentation and spaces help avoid them.
- Multiline statement continuation. Distinguish explicit line continuation with a backslash from implicit continuation inside delimiters, and describe the indentation allowed on a continuation line.
- Boolean values and operations. State that Python has a Boolean object type with the values True and False, and that an expression with a Boolean operation returns one of those values.
- Truth values of Python objects. Explain how Python treats numbers, strings, collections, and None in a Boolean context, and why file and code objects are poor choices for Boolean tests.
- Comparison membership and identity tests. Distinguish value equality from object identity, and describe how comparison and membership operators test objects.
- And or operand results. Trace which operand and or or returns and when evaluation stops.
- Word count program purpose. Describe what the example program reports and why the author uses it to introduce a Python program.
- Concise loop-centered program. Explain the section’s observation about where most of the example program’s work happens and what that illustrates about Python.
- AI refactoring prompt inputs. Describe how to request this refactoring from an AI chatbot: provide the existing code, ask for shorter code, and optionally ask it to count only alphabetic strings.
What it builds on
- The if-elif-else statement (chapter 3) · The earlier overview introduces the if-elif-else statement.
- Indentation and block structuring (chapter 4) · The earlier section introduces indentation and block structuring.
- List indices (chapter 5) · Uses the idea that list elements have indices.
- Packing and unpacking tuples (chapter 5) · Tuple packing and unpacking.
- Sets (chapter 5) · The distinction between sets and lists.
- What is a dictionary? (chapter 7) · Dictionaries store keys and values.
- Strings as sequences of characters (chapter 6) · Strings have been introduced as sequences of characters.
- Writing and running code in Colaboratory (chapter 2) · Earlier experience running code in Colaboratory notebooks.
Section by section
Introduction
Introduces the chapter’s coverage of Python control flow, including conditionals, loops, comprehensions, indentation, and Boolean expressions.
8.1 The if-elif-else statement
This section explains how Python’s if-elif-else statement selects a branch and what happens when clauses or bodies are omitted.
- Conditional branch selection: Trace how Python checks an if condition, then any elif conditions in order, and executes the body for the first true condition or the optional else body.
Why it matters: This lets you predict which code runs when a program makes a decision. - Optional clauses and required bodies: Explain that elif and else are optional, that a conditional with no true condition and no else does nothing, and that an if body must contain a statement even if it is only pass.
Why it matters: It helps you write a simple conditional without unnecessary branches while keeping its body valid.
Key terms: if, elif, else, condition, body, pass statement
8.2 Structural pattern matching with match
This section introduces match-case as structural pattern matching, explains how cases select code, and cautions that complex patterns need careful testing.
- Value and type matching: Explain how Python's match-case differs from a simple value-based switch: it can select among cases by matching equal values or types.
Why it matters: This distinction explains why match-case can express more than a value-only branch. - Case alternatives and fallback: Describe the kinds of case tests shown here, how `|` combines alternatives, and what happens with an optional `_` case or when no case matches.
Why it matters: These rules let you explain which branch runs, including when nothing matches. - Pattern matching caution: Justify the section's advice to read the documentation and test edge cases before using match-case.
Why it matters: Checking edge cases helps prevent surprising branch behavior.
Key terms: match-case statement, structural pattern matching, test_expression, or operator |, case for "_", pattern matching, edge cases
8.3 The while loop
This section explains how a while loop repeats, how its optional else block behaves, and how break and continue change the loop’s flow.
- While condition and loop body: Explain when a while loop executes its body, when it stops, and how indentation identifies its blocks.
Why it matters: This lets you trace whether a loop’s statements run at all and where its blocks end. - Optional while else block: Explain when a while loop’s optional else block runs and why it can be useful when the body contains a break.
Why it matters: The else block can distinguish ordinary loop completion from an early exit. - Break and continue effects: Distinguish what break and continue do when executed in a while loop’s body.
Why it matters: The distinction lets you trace whether the loop ends or merely moves to its next condition check.
Key terms: while loop, condition, body, post-code, indentation, else, break, flag, continue
8.4 The for loop
This section explains how Python for loops visit values from an iterable and how break, continue, and an optional else clause affect execution.
- Iteration over iterable values: Explain that a Python for loop takes successive values from an iterable rather than traditionally incrementing and testing a variable, and describe how its body runs once for each value.
Why it matters: It helps you read a for loop as processing values from a source, not necessarily counting upward. - For loop control statements: Distinguish what break and continue do in a for loop, and explain when the optional else block does not run.
Why it matters: These statements determine whether a loop stops entirely, moves to its next value, or reaches its optional else block.
Key terms: for loop, iterable object, item, body, break, continue, else, post-code
8.4.1 The range function
This subsection shows how to generate list indices for a for loop with range(len(...)) and explains why range uses little memory.
- List indices with range: Explain how range and len work together to supply a for loop with the indices of a list, such as when finding the positions of negative values.
Why it matters: This lets you loop over positions when you need to report where values occur, not just inspect the values. - On-demand range values: Describe what range creates instead of a list of integers and why that matters for a very large loop.
Why it matters: A loop can use a huge range of numbers without first storing all those numbers in a list.
Key terms: range, len, indices, for loop, range object, integers on demand
8.5 Controlling range with starting and stepping values
This section explains how starting, ending, and step arguments control the sequence produced by range.
- Range bounds and step values: Explain how range uses a starting value, an excluded ending value, and an optional step, including why a descending range needs a negative step.
Why it matters: These arguments let you choose where a range starts and how it counts without accidentally including the endpoint.
Key terms: range, starting value, ending value, step value
8.6 The for loop and tuple unpacking
Shows how tuple unpacking makes a for loop over pairs cleaner by assigning each pair’s elements to separate variables.
- Tuple unpacking in for loops: Explain how a for loop can unpack each two-element tuple into two variables, and why this makes the loop cleaner.
Why it matters: It lets you work directly with both values in each pair while keeping the loop readable.
Key terms: tuple unpacking, for loop, two-element tuples
8.7 The enumerate function
This section shows how enumerate pairs each list item with its index for clearer loops.
- Indexed iteration with enumerate: Explain how enumerate and tuple unpacking let a loop access both a list item and its index, and why this can be clearer than using range.
Why it matters: It makes loops that need both positions and values easier to read.
Key terms: enumerate function, tuple unpacking, index, item, range
8.8 The zip function
This section explains how zip pairs corresponding elements of iterables for use in a loop.
- Pairing iterables with zip: Explain that zip combines corresponding elements from two or more iterables into tuples and stops when the shortest iterable ends.
Why it matters: It lets you loop over related values together without assuming the iterables have the same length.
Key terms: zip function, iterables, tuples
8.9 List, set, and dictionary comprehensions
The section introduces comprehensions as concise ways to build lists, sets, and dictionaries while iterating over and optionally filtering a sequence.
- Comprehensions as loop shortcuts: Explain how a comprehension replaces a common for-loop pattern that processes items to create a new collection, optionally selecting which items to include.
Why it matters: This lets you recognize when a loop that builds a collection can be written more concisely. - Comprehension result types: Distinguish list, set, and dictionary comprehensions by the collections they create and the expressions they require.
Why it matters: The form of the comprehension determines what kind of collection you get.
Key terms: comprehension, for loop, conditional expression, list comprehension, set comprehension, dictionary comprehension, key and value expression
8.9.1 Generator expressions
Introduces generator expressions as a memory-efficient alternative to list comprehensions for producing values to iterate over.
- Generator expression behavior and benefit: Explain how a generator expression differs from a list comprehension in syntax and result, and why it can use less memory for large sequences.
Why it matters: You can produce values for a loop without holding an entire large list in memory.
Key terms: generator expression, generator object, iterator, list comprehension
8.10 Statements, blocks, and indentation
This section explains how indentation defines Python blocks, how indentation mistakes arise, and how to continue statements across lines.
- Indented blocks and nested statements: Explain how indentation marks the body of a compound statement and how putting a compound statement inside a block creates a nested block.
Why it matters: Indentation determines which statements belong to each control-flow clause. - Indentation consistency and errors: Describe why incorrectly aligned statements raise exceptions and how consistent indentation and spaces help avoid them.
Why it matters: Visually similar indentation can still put statements at different levels or cause an exception. - Multiline statement continuation: Distinguish explicit line continuation with a backslash from implicit continuation inside delimiters, and describe the indentation allowed on a continuation line.
Why it matters: This lets you split long statements without mistaking continuation-line spacing for a new block. - String continuation and concatenation: Explain the indentation hazard when breaking a string with a backslash and the alternative of quoting separate segments.
Why it matters: Splitting a string carelessly can insert unwanted whitespace into its value. - Interactive shell blank line: Describe when the basic interactive shell requires an extra line after indented code and where that line is unnecessary.
Why it matters: The extra line is a shell-input requirement, not a requirement for code in every environment.
Key terms: block, body, compound statement, clause, nested blocks, indentation, tabs, spaces, four spaces, backslash
8.11 Boolean values and expressions
Introduces Python’s Boolean values and the result of Boolean operations in the context of conditional tests.
- Boolean values and operations: State that Python has a Boolean object type with the values True and False, and that an expression with a Boolean operation returns one of those values.
Why it matters: This gives you the basic vocabulary for discussing conditional tests in Python.
Key terms: Boolean object type, True, False, Boolean operation
8.11.1 Most Python objects can be used as Booleans
This subsection explains how Python treats common objects as true or false in a Boolean context.
- Truth values of Python objects: Explain how Python treats numbers, strings, collections, and None in a Boolean context, and why file and code objects are poor choices for Boolean tests.
Why it matters: This lets you predict what a condition means when it contains a value rather than an explicit comparison.
Key terms: Boolean context, False, True, None
8.11.2 Comparison and Boolean operators
This section explains comparison and Boolean operators, including membership and identity tests, compound conditions, and how and/or return operands.
- Comparison membership and identity tests: Distinguish value equality from object identity, and describe how comparison and membership operators test objects.
Why it matters: Choosing between equality, identity, and membership tests changes what a condition asks. - Compound Boolean conditions: Explain how and, or, and not combine Boolean expressions, how Python can write a range test as a chained comparison, and why parentheses can help with precedence.
Why it matters: Clear compound conditions make control flow easier to read and less prone to misinterpretation. - And or operand results: Trace which operand and or or returns and when evaluation stops.
Why it matters: An and or or expression can produce an operand itself, not just True or False.
Key terms: ==, !=, in, not in, is, is not, and, or, not, precedence
8.12 Writing a simple program to analyze a text file
The section uses a small word-counting program to illustrate how concise a Python program can be and how to run it against a sample file.
- Word count program purpose: Describe what the example program reports and why the author uses it to introduce a Python program.
Why it matters: The example gives you a concrete picture of what this small Python program is meant to do. - Concise loop-centered program: Explain the section’s observation about where most of the example program’s work happens and what that illustrates about Python.
Why it matters: It connects the example’s compact structure to the author’s point about Python’s conciseness. - Sample file test setup: Describe the stated ways to run the example against its sample file and the file-location condition for getting the shown output.
Why it matters: The sample file setup matters if you want to reproduce the example’s output.
Key terms: UNIX wc utility, lines, words, characters, for loop, idiomatic, conciseness, word_count.py, word_count.tst, notebook
8.13 Refactoring word_count
This section poses an exercise to shorten a word-count program, with an optional change to count only alphabetic strings.
8.13.1 Solving the problem with AI-generated code
This subsection explains what to give an AI chatbot when asking it to refactor existing word-counting code.
- AI refactoring prompt inputs: Describe how to request this refactoring from an AI chatbot: provide the existing code, ask for shorter code, and optionally ask it to count only alphabetic strings.
Why it matters: A specific request tells the chatbot both what to rewrite and what improvement you want.
Key terms: refactoring, AI chatbot, alphabetic strings
8.13.2 Solutions and discussion
8.14 Summary
Where this is used later
- Generator functions (chapter 9) · The while loop provides the section’s example of limiting iterations.
- Basic function definitions (chapter 9) · Indentation marks blocks of Python code.
- What is a regular expression? (chapter 16) · Interpreting Python objects in a Boolean context.
- Creating a program (chapter 11) · The earlier text-file analysis program provides the starting point for counting file statistics.
- Solving the problem with AI-generated code (chapter 9) · The earlier exercise asked AI tools to refine existing code at the line level.
Concepts explained in this chapter
- indentationWhitespace placed at the beginning of source lines to visually align code and, in Python, delimit nested blocks.
- generator expressionA generator expression is a Python expression that lazily produces values from an iteration specification without constructing the complete result collection in memory.
- comprehensionA list comprehension is a Python expression that constructs a list by iterating over an iterable and optionally filtering or transforming its elements.
- statementA statement is a syntactic unit representing an executable instruction in a programming language.
- loopA for loop is a control-flow construct that iterates over the items supplied by an iterable.
- booleanA boolean value is a truth-valued value that is either true or false.
- blockA code block is a sequence of one or more statements grouped as a syntactic unit and executed under a common control structure.
- character countA character count is the number of characters contained in a file or text.
- lines of codeA line count is the number of lines contained in a text file or text representation.
- word countA word count is the number of words identified in a text according to a specified word-segmentation rule.
- conditional logicA conditional statement is a programming-language construct that selects code for execution based on a condition.
- refactoringRefactoring is the systematic restructuring of existing source code to improve its internal qualities without changing its externally observable behavior.
- escape characterA backslash is the character used in Python string literals and regular-expression patterns to introduce escape sequences or special interpretations.
- tab characterA tab character is a whitespace character that represents horizontal spacing in source text.
- else clauseAn else clause is the optional part of a try statement that executes only when its try block completes without raising an exception.
- newlineA newline is a character or character sequence that marks the boundary between consecutive lines of text.
- readlinesreadlines is a file-object method that reads all remaining lines from an open stream and returns them as a list.
- splitsplit is a string method that divides a string into a list of substrings according to a separator or, by default, whitespace.
- membership operatorThe in operator is a Python comparison operator that tests whether a value is contained in a collection.
- operatorAn operator is a language construct that performs an operation on one or more operands, including path construction with pathlib operands.
- PythonPython is a high-level general-purpose programming language with an interpreted execution model and dynamic features.
- NoneNone is Python's singleton object representing the absence of a value.
- zipzip is a Python built-in function that aggregates corresponding elements from two or more iterables into tuples, stopping when the shortest iterable is exhausted.
These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.
