Skip to content
dreamcode
dreamcode
Map
While loops
Lesson 16 of 77
+15 XP on finish
PYTHON BASICSChapter 3 · Loops and iteration

Looping while true

A while loop keeps running as long as a condition remains True. You must make sure the condition eventually becomes False, or your loop will run forever (an infinite loop).

Worked example

How it reads

  • while stars > 0: checks the condition before each turn
  • stars = stars - 1 decreases the counter so the loop eventually stops
Cloud tip: Always modify the variable in your condition inside the loop body, otherwise you will get stuck in an infinite loop.
main.py
PYTHON
real Python, runs in your browser
Console
Run your code to see its output here.
YOUR TURN

Start with n = 1 and use a while loop to keep doubling it while it is 100 or less. Print the result: 128.

Press Run to check your work.