Write the Steps Once
In the strings lesson you wrote the same three lines four times, once per reading. Real data has thousands of readings. A loop writes the steps once and repeats them for each value; a condition chooses what to do with each one. This lesson shows how Python writes both, and a shorter form, the comprehension, that builds a new list in one expression.
Indentation Is the Structure
Python groups lines by indentation, not by braces or end keywords. The
lines under a line ending in a colon, indented by four spaces, form its
block:
if reading > limit:
label = "high"
print(label)
print("done")
The two indented lines run only when the condition is true; print("done")
always runs. Mixing tabs and spaces, or indenting by different amounts in one
block, stops the program with an IndentationError. Most editors insert four
spaces when you press Tab in a .py file.
Conditions
if, elif (else if) and else choose one block. Python checks them from
the top and runs the first block whose condition is true:
if reading > limit:
label = "high"
elif reading > limit - 1:
label = "near the limit"
else:
label = "normal"
Conditions can be combined with and, or and not.
for Loops
A for loop takes each item of a collection in turn:
for reading in readings:
print(reading)
reading is a variable that the loop sets to each item. range() produces
whole numbers to loop over:
print(list(range(3)), list(range(1, 4)), list(range(0, 10, 4)))
[0, 1, 2] [1, 2, 3] [0, 4, 8]
Like a slice, range(start, stop) stops before stop; a third number sets
the step.
Two built-in functions help when you need more than the item.
enumerate(items, start=1) gives each item with its position, and
zip(names, values) pairs items from two lists:
print(list(zip(["D1", "D2", "D3"], [21.5, 19.0])))
[('D1', 21.5), ('D2', 19.0)]
zip() stops at the shorter list without any warning, so D3 silently
disappears. Check that paired lists have the same length.
Inside a loop, continue skips to the next item and break leaves the loop:
for n in range(5):
if n == 1:
continue
if n == 3:
break
print(n)
This prints 0 and 2: 1 is skipped, and the loop ends at 3.
while Loops
A while loop repeats as long as its condition is true. Use it when you do
not know in advance how many times to repeat, for example "until the first
reading above the limit". Make sure something in the block changes the
condition; otherwise the loop never ends. If that happens, press Ctrl+C to
stop the program.
Comprehensions
A very common loop builds a new list from an old one. A list comprehension writes that loop as a single expression:

Read the diagram from top to bottom and match the colours. The green part is
what goes into the new list, the blue for clause says where the values come
from and the orange if clause, which is optional, says which ones to keep.
The comprehension is usually written on one line:
above = [reading for reading in readings if reading > limit].
The value in front can be any expression, and curly braces with a
key: value pair build a dictionary instead:
print([r * 2 for r in [1, 2, 3]], {d: len(d) for d in ["D1", "D10"]})
[2, 4, 6] {'D1': 2, 'D10': 3}
Use a comprehension when it reads clearly as "the list of these, from there,
where this holds". When a loop needs several steps, print calls or break,
keep the loop.
Exercise: Filter, Label and Pair Readings
You will process six readings with loops, then confirm that a comprehension gives the same result.
Starting state: the course environment from the setup lesson, active in your terminal.
-
Create the exercise folder. macOS and Linux:
mkdir -p ~/pyml-practice/filter-readings cd ~/pyml-practice/filter-readingsWindows PowerShell:
mkdir $HOME\pyml-practice\filter-readings cd $HOME\pyml-practice\filter-readings -
Save this as
readings.pyin that folder:"""Filter, label and pair readings with loops and comprehensions.""" devices = ["D1", "D2", "D3", "D4", "D5", "D6"] readings = [21.5, 19.0, 26.2, 24.6, 27.8, 22.3] limit = 25.0 count = 0 for reading in readings: if reading > limit: count = count + 1 print("Readings above the limit:", count) above = [] for reading in readings: if reading > limit: above.append(reading) print("Loop:", above) above_short = [reading for reading in readings if reading > limit] print("Comprehension:", above_short) print("Same result:", above == above_short) for position, reading in enumerate(readings, start=1): if reading > limit: label = "high" elif reading > limit - 1: label = "near the limit" else: label = "normal" print(position, reading, label) status = {device: reading > limit for device, reading in zip(devices, readings)} print("Above the limit:", status) -
Predict the count and the label for position 4, then run it:
python readings.pyOutput (every value should match):
Readings above the limit: 2 Loop: [26.2, 27.8] Comprehension: [26.2, 27.8] Same result: True 1 21.5 normal 2 19.0 normal 3 26.2 high 4 24.6 near the limit 5 27.8 high 6 22.3 normal Above the limit: {'D1': False, 'D2': False, 'D3': True, 'D4': False, 'D5': True, 'D6': False}
How the Script Works
The first loop is the readiness procedure from the first lesson in Python:
count starts at 0, and the indented if adds 1 for each reading above the
limit. The second loop builds a list the same way, and the comprehension
builds the same list in one line; above == above_short compares the two
lists item by item and prints True.
The enumerate loop numbers the readings from 1 and uses if, elif and
else to give each a label. Reading 4 is 24.6: it is not above 25.0, but it
is above 24.0, so the elif branch labels it "near the limit". Order
matters: if the elif came first, 26.2 would also be labelled "near the
limit", because it is above 24.0 too.
The last line is a dictionary comprehension. zip(devices, readings) pairs
each device with its reading, and the comprehension maps each device to the
result of reading > limit.
If you changed limit = 25.0 to limit = 27.0, the count would become 1 and
only 27.8 would be labelled high; 26.2 would become "near the limit".
Success: every line matches the output above, and Same result is
True.
If something differs:
| What you see | Likely cause | Next step |
|---|---|---|
IndentationError | A block is indented unevenly, or tabs and spaces are mixed | Indent every block by four spaces |
| The count is printed six times | The print line is indented inside the loop | Move it back to the left margin |
| Every reading labelled "near the limit" or "high" | The elif and if conditions are in the wrong order | Test the strictest condition first |
| Fewer entries in the dictionary than devices | The two lists have different lengths | Make them the same length; zip() stops at the shorter |
Independent task: add a while loop to the end of the script that stops
at the first reading above the limit and prints it with its position counted
from 1 (First reading above the limit: 26.2 at position 3). Make it print
No reading is above the limit instead when none is, and check that by
changing the limit to 30.0. Predict what happens if your loop forgets to
check whether it has reached the end of the list.
-
Clean up. macOS and Linux:
cd ~/pyml-practice ls rm -rf filter-readingsWindows PowerShell:
cd $HOME\pyml-practice ls Remove-Item -Recurse filter-readingsCheck that
lsshowsfilter-readingsbefore you remove it. Keep.venv.
Check Your Understanding
- How many times does the body of
for n in range(2, 10, 3):run, and with which values? - What does
[r for r in [21.5, 26.2, 27.8] if r > 30]give? - A loop labels readings with
if reading > 20: ... elif reading > 25: .... Why is a reading of 26 never labelled by the second branch?
Answer and Reasoning
Independent task
position = 0
while position < len(readings) and readings[position] <= limit:
position = position + 1
if position < len(readings):
print("First reading above the limit:", readings[position], "at position", position + 1)
else:
print("No reading is above the limit")
The loop moves position forward while the current reading is at or below
the limit. It stops at index 2, the reading 26.2, which is position 3 counted
from 1. With the limit at 30.0 no reading stops it, so position reaches 6,
the length of the list, and the else branch runs. The order of the two
conditions matters: and checks position < len(readings) first and does not
evaluate the second condition once the first is false. Without that check,
readings[6] would be evaluated and the program would stop with
IndexError: list index out of range.
Understanding check
- Three times, with 2, 5 and 8:
rangestarts at 2, steps by 3 and stops before 10. - An empty list,
[]: no reading is above 30, so nothing is kept. - Python runs the first branch whose condition is true. 26 is greater than
20, so the first branch runs and the
elifis never checked. Put the stricter condition,reading > 25, first.