Skip to content
Justice Tech School

While Loops

A while loop keeps running while its condition is True. Make sure something inside changes the condition, or the loop never ends. while True with a break is a common way to repeat until something happens.

Example
n = 3
while n > 0:
    print("Countdown", n)
    n -= 1
print("Liftoff")

total = 0
while True:
    total += 10
    if total >= 30:
        break
print(total)

Result

Countdown 3
Countdown 2
Countdown 1
Liftoff
30

Exercise

Subtract one each time.

while n > 0:
    n  1

Quiz Test

How do you leave a loop early?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.