while loops
A while loop repeats its block as long as its condition stays True:
n = 3 while n > 0: print(n) n -= 1 # without this the loop never ends!
Each pass through the loop is called an iteration.
n box drops 3, 2, 1, 0. When it reaches 0, n > 0 is False and the loop ends.See it run
coins = 1 days = 0 while coins < 10: coins = coins * 2 days = days + 1 print(days, coins)
A while loop re-checks its condition before every pass. Watch coins double until the test fails.
Practice while loops
Exercise 1
Count down from n = 5 with a while loop, printing 5, 4, 3, 2, 1 on separate lines, then print Liftoff!.
Exercise 2
A delivery robot has battery = 14. Each trip uses 4 units. Use a while loop to make as many complete trips as possible; store the count in trips and the remaining battery in battery. Print Trips: 3 then Battery: 2.
Exercise 3
A fundraiser starts at saved = 2 and doubles it each day. Use a while loop until savings first reach or exceed target = 25. Store days and saved, then print 4 days: 32. Do not stop a day early or run an extra day.
The explanation and tasks are public. Running this lesson requires an account with course access.
Practice
Loading Python…Visualizer Watch your code run line by line
Run your code, then choose Play to follow its execution.