Python course / Foundations
Loops
Repeat work with while and for, and walk a sequence while keeping totals, positions and flags straight. Loops are where beginners lose the most time, usually to a stop condition that never fires or a total started in the wrong place.
- while
- for
- range
- break and continue
- enumerate
- zip
- running totals
- flags
Runs in your browser. Start straight away; create an account when you want your progress kept.
readings = [4, 7, 7, 2, 9]
total = 0
highest = readings[0]
for position, value in enumerate(readings, start=1):
total += value
if value > highest:
highest = value
print(f"reading {position}: {value}")
print("total:", total)
print("highest:", highest)
reading 1: 4 reading 2: 7 reading 3: 7 reading 4: 2 reading 5: 9 total: 29 highest: 9
What you will learn
- Repeat a block for as long as a condition holds.
- Loop over a sequence of numbers, with the stop excluded.
- Stop a loop as soon as it has found what it was looking for.
- Loop over items and their positions together.
- Walk two lists side by side, and notice when they do not line up.
- Join pieces into one string without a stray separator at the end.
The lessons in this module
- while
- Loops that never end
- for over a string
- range
- Steps and counting down
- Running totals
- Biggest and smallest
- break
- continue
- Controlling the step yourself
- Nested loops
- for with else
- enumerate
- zip
- Asking until the answer is valid
- Reading until a stop word
- Reading in the condition
- Backwards and by position
- Building text in a loop
- Several results in one pass
- Watching a loop run
- Remembering the previous item
- Flags that stay set
- Module review: receipt reader
Ready when you are
Previous: Conditions and branching. Next: Lists. All modules are on the course page.