PythonLesson 8 of 16

while loops in Python

while repeats code as long as a condition holds. It shines when the number of steps is unknown: how many weeks to save, how long a battery lasts.

Key points

  • while condition: repeats the body while the condition is True
  • Something inside must change, or the loop never ends
  • break leaves the loop at once
  • continue skips the rest of this round and starts the next
  • If a program hangs, look for the variable that never changes

Example

battery = 100hours = 0while battery > 20:    battery -= 15    hours += 1print(f"After {hours} h the battery is at {battery}%") n = 0while True:    n += 1    if n == 3:        breakprint("Stopped at", n)

The battery loses 15% an hour while it is above 20%. The while True loop looks endless, but break stops it at three.

Task

How to use the editor⌘ Enter or Ctrl Enter runs the code, ⇧ ⌘ Enter checks the task.Tab and Shift Tab indent the line or the selection; Esc, then Tab leaves the editor.The check compares what the program printed with the task; spaces at line ends do not matter.After two failed checks you may open the solution. Your code is kept in this browser.

You put aside 700 a week and the goal is 5000. Use while to find how many weeks it takes (weeks) and how much ends up saved (saved).

Output

What your program prints appears here.