Chapter 3
Branches and Loops
Comparisons, if/elif/else, for loops, while loops, running totals, and off-by-one errors.
What this chapter does
Once the reader can name values and inspect types, Python can choose and repeat. This chapter teaches conditions, branches, loops, and the boundary habits that keep repeated computation honest.
Lessons
Read these in order.
The chapter opening gives the main idea. Move through these lessons next; each page reuses ideas from the pages before it.
- 01Conditions and Comparisons
Comparisons as boolean expressions used for decisions.
- 02if, elif, and else
Ordered branch checks, indentation, and fallback cases.
- 03for Loops and Ranges
Repeating over sequences and ranges while tracking loop variables.
- 04while Loops
Repeating while a condition remains true and making sure the condition can change.
- 05Running Totals
Accumulating values across loop iterations.
- 06Off-by-One Errors
Boundary mistakes caused by start values, stop values, counts, and indexes.
You are ready when
- Use comparisons as conditions.
- Trace if, elif, and else branches in order.
- Use for loops with lists and ranges.
- Use while loops when repetition depends on a condition.
- Compute a running total.
- Recognize off-by-one boundary mistakes.
Where this leads
- Functions
- Collections and Iteration
- Files, Paths, and Modules