01 / 20

While Loops
in Python

Master condition-based repetition to make your programs loop until a goal is reached: from simple counters to input validation and beyond.

Python

What Is a Loop?

A loop tells the computer to repeat a block of code multiple times instead of writing the same instructions over and over. Loops are one of the most powerful ideas in programming: they let a few lines do the work of thousands.

Repetition
Execute the same code again and again without duplicating it.
Condition
Keep going as long as a test evaluates to True.
Termination
Stop when the condition becomes False.

The while Statement

A while loop checks a condition before each iteration. If the condition is True, the indented body runs. Then Python jumps back to check again. This cycle continues until the condition becomes False.

while condition: # body: runs while condition is True statement_1 statement_2

How a While Loop Flows

Start condition True? True Body loop back False Exit loop

Anatomy of a while Loop

count = 0 # 1. Initialise while count < 5: # 2. Condition print(count) # 3. Body count += 1 # 4. Update
1
Initialise a variable before the loop starts.
2
Condition is tested at the top of every iteration.
3
Body executes only while the condition is True.
4
Update changes the variable so the loop can eventually stop.

while vs for

Python has two main loops. Choose the right one based on whether you know in advance how many times to repeat.

while loop for loop
Repeat count Unknown in advance Known or iterable
Controlled by A boolean condition A sequence or range
Risk of infinite loop Higher: you manage the update Lower: auto-advances
Best for Input validation, games, search Iterating lists, counted reps

How to Write a While Loop

1
Identify the stopping condition. What must be true for the loop to keep going?
2
Initialise variables that the condition depends on before the loop.
3
Write the condition after the keyword while, followed by a colon.
4
Indent the body with the actions to repeat each iteration.
5
Update the control variable inside the body so the condition eventually becomes False.
6
Trace through mentally: walk through 2-3 iterations to verify correctness.

Example 1: Countdown

n = 5 while n > 0: print(n) n -= 1 print("Liftoff!")
n = 5 print 5 → n = 4 print 4 → n = 3 print 3 . . . n = 1 print 1 → n = 0 Exit loop

Example 2: Input Validation

A very common use of while: keep asking the user for input until they give a valid answer.

age = -1 while age < 0 or age > 120: age = int(input("Enter your age: ")) print("Your age is", age)

Example 3: Sentinel Value Pattern

A sentinel value is a special input that signals "stop". The loop keeps running until it sees the sentinel.

total = 0 num = int(input("Number (-1 to quit): ")) while num != -1: total += num num = int(input("Number (-1 to quit): ")) print("Sum =", total)

break and continue

break
Immediately exits the loop, skipping any remaining iterations and the condition check.
continue
Skips the rest of the current iteration and jumps back to the condition check.
while True: cmd = input("> ") if cmd == "quit": break # exit immediately if cmd == "": continue # skip blank input print("You typed:", cmd)

The else Clause on Loops

Python uniquely lets you attach an else block to a while loop. The else body runs only if the loop finishes normally (condition became False) and does not run if the loop was terminated by break.

n = 10 while n > 1: if n % 2 == 0: print(n, "is even, not prime") break n -= 1 else: print("No even number found")

Infinite Loops

An infinite loop occurs when the condition never becomes False. Your program freezes and must be forcibly stopped.

# BUG: x never changes! x = 1 while x < 10: print(x) # forgot: x += 1
x = 1 print 1 → x = 1 print 1 → x = 1 print 1 → . . . forever

Common Mistakes

✕ Forgetting the Update
The control variable never changes, causing an infinite loop. Always modify the variable inside the body.
✕ Off-by-One Error
Using \( < \) instead of \( \leq \) (or vice versa), so the loop runs one time too many or too few.
✕ Wrong Condition Logic
Using and when you need or (or vice versa), causing the loop to exit too early or never at all.

While Loop Cheat Sheet

Concept Syntax / Keyword Purpose
Basic loop while condition: Repeat while True
Infinite loop while True: Loop until break
Early exit break Leave loop immediately
Skip iteration continue Jump to next check
Completion block else: Runs if no break
Sentinel pattern Priming read + loop Stop on special value

Question 1 of 5

What is the output of this code?

x = 3 while x > 0: print(x, end=" ") x -= 1

Question 2 of 5

Which keyword immediately exits a while loop?

Question 3 of 5

How many times does the body of this loop execute?

i = 10 while i < 10: print(i) i += 1

Question 4 of 5

What happens if you forget to update the control variable inside a while loop?

Question 5 of 5

What is the value of total after this code runs?

total = 0 n = 1 while n <= 4: total += n n += 1