Skip to main content

P01.3 · Control flow

A free, illustrated module of 4 lessons and one interactive in P01 Python from Zero: Choosing a path: if, elif and else; Repeating with while; Repeating with for and range; Loop patterns: accumulate, count, search.

P01.3 L0 · Foundation 4 lessons · about 100 min Live · in review

Part of P01 Python from Zero in the Programming and Data track.

Until now a program ran every one of its lines once, from top to bottom. These four lessons teach it to choose and to repeat: if, elif and else run one block out of several, with the first true test winning; a while loop repeats a block for as long as a test holds; a for loop visits each item of a string, a range or a list in turn; and three loop patterns, a running total, a count and the best so far, turn a list of scores into one answer, with break and continue for leaving early.

What you need first. Values, names and assignment (P01.2.1 and P01.2.2), whole-number division and remainder (P01.2.3) and comparisons with True and False (P01.2.4), plus print and trace tables from P01.1.1. The second lesson rebuilds the binary form of 13 from P01.1.4.

Lessons

  1. Choosing a path: if, elif and else P01.3.1 25 min

    A program can test a condition and run one block of lines or another. Learn if, elif and else, read them as flow charts, band the five quiz scores with cut-offs 70 and 50, and see which values Python counts as true.

  2. Repeating with while P01.3.2 25 min

    A while loop runs its block again and again for as long as its test holds. Trace one pass by pass, halve 13 down to 0 to rebuild its binary form 1101, and learn the start, test and update every loop needs, the loop that never ends and the count that is off by one.

  3. Repeating with for and range P01.3.3 25 min

    A for loop binds a name to each item of a string, a range or a list in turn and runs its block once per item. Learn what range gives and why its stop is never reached, rewrite a for loop as a while loop, and trace a loop inside a loop over a grid.

  4. Loop patterns: accumulate, count, search P01.3.4 25 min

    Three loop patterns turn a list into one answer: a running total (300, so the mean of the scores is 60.0), a count (4 passes) and the best so far (80). Add a search that stops early with break, skip items with continue, and check every answer against sum, len, max and min.

The interactive

P01.3-X1 · Flow-chart tracer. Three small programs, each beside its flow chart: an if, elif, else that bands a score, a while loop that halves a number and a for loop that totals the scores. Set the input with the slider and step through: the line and the box light up together, the names and the output update, and a counter shows how many times the loop body has run. It lives in Repeating with for and range.

Back to top