When Should You Use a While Loop?
Use a while loop when you do not know in advance how many iterations are needed. For example, reading user input until they type "quit", or running a game until the player loses. If you already know the count, a for loop is cleaner.
Basic Syntax
count = 0
while count < 5:
print(count)
count += 1
The loop body runs while the condition is True. Forgetting to update count creates an infinite loop โ the #1 beginner bug.
Breaking Out Early
while True:
answer = input("Type 'quit' to exit: ")
if answer == "quit":
break
print(f"You said: {answer}")
Skipping Iterations with continue
n = 0
while n < 10:
n += 1
if n % 2 == 0:
continue
print(n) # prints odd numbers only
While vs For: Choosing the Right Loop
- For loop โ known count, iterating over a sequence.
- While loop โ unknown count, condition decides when to stop.
Common HKDSE Pattern: Input Validation
age = -1
while age < 0 or age > 120:
age = int(input("Enter your age: "))
print(f"Age accepted: {age}")
๐ก Tip: Always guarantee your loop variable changes inside the body, or structure your loop around a
break. That single habit eliminates most infinite-loop bugs.Practise this on PyForm โ free
PyForm runs Python in your browser with an AI tutor trained for HKDSE. No install, no credit card.
Open PyForm โ