Level 1
0 / 100 XP

While loops

A for loop repeats a known number of times — once per item, or once per number in a range. But sometimes you don't know how many repetitions you'll need in advance. You just want to keep going while something is true. That's a while loop.

The while loop

A while loop repeats its block as long as a condition stays True:

Python
count = 1 while count <= 3: print(count) count = count + 1

Output:

Text
1 2 3

Here's what happens each pass:

  • Python checks the condition count <= 3
  • If it's True, it runs the block
  • Then it checks again — and stops as soon as the condition is False

You must change the condition inside the loop

Look closely at count = count + 1. Without it, count would stay 1 forever, the condition would always be True, and the loop would never stop — an infinite loop.

Python
# DON'T run this — it never ends count = 1 while count <= 3: print(count) # count never changes -> infinite loop

Every while loop needs something inside it that eventually makes the condition False.

Counting down

while loops are natural for counting down:

Python
n = 3 while n > 0: print(n) n = n - 1 print("Liftoff!")

Output:

Text
3 2 1 Liftoff!

for vs while — which to use?

  • Use a for loop when you know how many times to repeat (every item in a list, every number in a range).
  • Use a while loop when you repeat until some condition changes and you don't know the count ahead of time.

Key takeaways

  • A while loop repeats its block as long as its condition is True
  • Always change something inside the loop so the condition eventually becomes False
  • Forgetting to do that creates an infinite loop that never stops
  • Reach for for when the count is known, while when it depends on a condition