Module 9 of 15 · Step 1 of 12

while Loops

A while loop repeats while a condition is True. Unlike a for loop, it does not automatically move to the next value. You must update something so it can stop.

By the end of this lesson, you can:
  • Write a stopping condition
  • Update a loop variable
  • Count upward and downward
  • Recognize an infinite loop
  • Repeat input until a match
while Loops lesson progress0%

Course progress: 0% · 0 of 12 steps completed in this module

Learn · Repeat while a condition is true
Concept 1 of 5

Repeat while a condition is true

Python checks the condition before every repetition. When it becomes False, the loop ends. The body must be indented and should change a value used by the condition.

Pattern
while condition:
    instruction
    update
Code
count = 1
while count <= 4:
    print(count)
    count += 1
Output
1
2
3
4

Why it works

  1. count starts at 1.
  2. The condition allows values through 4.
  3. count increases each time; at 5 the loop stops.

Common mistake

Not this
while count <= 4:
    print(count)
Try this
while count <= 4:
    print(count)
    count += 1

Without an update, count never changes and the loop may run forever.