Lesson 5 of 10
A while loop repeats a block of code for as long as its condition is True. It checks the
condition, runs the body, then checks again — over and over.
count = 1
while count <= 5:
print(count)
count = count + 1
print("Done!")
Read it as: "while count is less than or equal to 5, print it and add one."
Like if, a while needs a colon and an indented body.
The three parts of every loop
Nearly every while loop has these, and forgetting any one causes a bug:
- Setup — a variable exists before the loop (
count = 1). - Condition — something that will eventually become
False(count <= 5). - Update — the body changes the variable (
count = count + 1).
Infinite loops
If the condition never becomes False, the loop never stops:
count = 1
while count <= 5:
print(count)
That prints 1 forever, because nothing ever changes count. If you run something like this
in the editor below and it hangs, click Reset. The fix is almost always a missing update
step.
Shorthand: +=
count = count + 1 is so common that Python has a shortcut:
count = 0
count += 1
count += 5
print(count)
-=, *=, and /= work the same way.
Counting down
Loops can go in any direction — just adjust the condition and the update.
countdown = 3
while countdown > 0:
print(countdown)
countdown -= 1
print("Liftoff!")
Try it yourself
Print the numbers 1 through 5, one per line, using a while loop.
Checkpoint
whilerepeats as long as its condition staysTrue.- Every loop needs setup, a condition that can end, and an update.
- Forgetting the update creates an infinite loop.
+=is shorthand for "add to this variable."
Questions about this lesson
Log in to ask a question.