DMarlon Studio

Lesson 8 · 8 of 20

Repeating with while · Python

Repeat code in Python with while as long as a condition holds: save up for a bike week by week and run a countdown.

Python · Repeating with while in DMarlon Studio: the example's code and its output in the terminal

while repeats its block as long as the condition is true. Before each round, Python checks savings < goal again: with 0, 22, 44, 66 and 88 euros it carries on; at 110 the condition is false and the loop stops.

Something inside the loop must change so that it ends one day. week += 1 is a short way of writing week = week + 1, and savings += 22 adds the week's savings. If nothing changed, the loop would never end (an infinite loop).

After the loop, the variables keep their last value: that is how the program can say it took 5 weeks and there are 10 euros to spare.

The countdown goes the other way: it starts at 3 and subtracts with count -= 1 until count > 0 is no longer true. Then the unindented line after it runs: «Lift-off!».

Code · main.py

# Saving for a bike: add money every week until you have enough.goal = 100savings = 0week = 0while savings < goal:    week += 1       # the same as week = week + 1    savings += 22    print(f"Week {week}: {savings} euros saved")print(f"Goal reached in {week} weeks!")print(f"Change left over: {savings - goal} euros")# A countdown: the loop stops when the condition becomes false.count = 3while count > 0:    print(count, "...")    count -= 1print("Lift-off!")

Output · python3 main.py

Week 1: 22 euros saved
Week 2: 44 euros saved
Week 3: 66 euros saved
Week 4: 88 euros saved
Week 5: 110 euros saved
Goal reached in 5 weeks!
Change left over: 10 euros
3 ...
2 ...
1 ...
Lift-off!

Key points

  • while condition: repeats while the condition is True.
  • Something in the loop must bring it closer to the end.
  • x += 1 adds 1 to x; x -= 1 subtracts 1.
  • If the condition is false from the start, the block never runs.

Exercise

Change the savings so that each week you put away 5 euros more than the week before (22, 27, 32…) and find out how many weeks it takes to buy a 250-euro bike.