Lesson 10 of 21 · 3 min
while Loop — Repeat While Condition is True
The WHY — Why while Loops?
Imagine you are pressing the snooze button on your alarm. You keep pressing snooze while you are tired. The moment you feel awake, you stop. You do not know in advance how many times you will press snooze — you keep going based on a condition.
This is a while loop: keep repeating this code while this condition remains True.
Basic while Syntax
count = 1 # start counting from 1
while count <= 5: # keep looping as long as count is 5 or less
print(count) # display current count value
count = count + 1 # CRITICAL: increase count each time to avoid infinite loop
Output: 1 2 3 4 5
What happens step by step:
- count = 1. Is 1 <= 5? Yes → print 1, count becomes 2
- count = 2. Is 2 <= 5? Yes → print 2, count becomes 3
- count = 3. Is 3 <= 5? Yes → print 3, count becomes 4
- count = 4. Is 4 <= 5? Yes → print 4, count becomes 5
- count = 5. Is 5 <= 5? Yes → print 5, count becomes 6
- count = 6. Is 6 <= 5? No → loop ends
Practical while Example — PIN Entry
correct_pin = "1234" # the correct PIN code
attempts = 0 # count how many tries have been made
while attempts < 3: # allow maximum 3 attempts
pin = input("Enter PIN: ") # ask user to enter PIN
if pin == correct_pin: # check if the entered PIN matches
print("Access granted!") # correct PIN — let them in
break # exit the loop immediately
else:
attempts = attempts + 1 # wrong PIN — add to attempt count
remaining = 3 - attempts # calculate remaining tries
print(f"Wrong PIN. {remaining} attempts left.") # tell userOutput: Enter PIN: 9999 Wrong PIN. 2 attempts left. Enter PIN: 1234 Access granted!
WARNING: The Infinite Loop
Forgetting to update the condition variable causes the loop to run forever:
x = 1
while x > 0: # x is always 1 — this condition is ALWAYS True
print(x) # runs forever! Press Ctrl+C to force-stop the program
# FORGOT to add: x = x + 1 or x -= 1 or something that changes x
If your program seems "frozen" or keeps printing endlessly, press Ctrl+C to stop it.
