Module 3 · Loops in Python · Lesson 1 of 6
The while loop
A while loop repeats a block of code as long as a condition stays True. Python checks the condition; if it's True, it runs the indented body, then loops back and checks again — over and over, until the condition finally turns False.
n = 3while n > 0:?print(n)n -= 1
The shape mirrors the if you already know: while, a condition, a colon, then an indented body. The crucial difference is that the body can run many times. Which means something inside the loop must eventually make the condition False — here, n -= 1 — or the loop would never stop.
Trace it: n starts at 5 and counts down, printing each value, until n reaches 0 — at which point n > 0 is False and the loop ends. The un-indented "Lift off!" then runs once.
A while loop can have an else clause too — an unusual but handy extra. The else block runs once, right after the loop ends naturally (when the condition becomes False). You'll see later it's skipped if the loop is cut short by a break.