Loops · Lesson 12 of 39
while Loops, break and continue
A for loop is perfect when you know what you are looping over. But sometimes you only know when to stop: keep asking until the password is right, keep doubling until the money reaches a target. That is the job of the while loop.
In this lesson
- How a
whileloop checks its condition breakto stop early andcontinueto skip- The
while True+breakpattern - The little-known
elseclause on loops
The while loop
savings = 1000
months = 0
while savings < 2000:
savings *= 1.08 # 8% growth per month (optimistic!)
months += 1
print(f"Doubled after {months} months: ₹{savings:.0f}")
Doubled after 10 months: ₹2159
The while cycle
- Check the conditionsavings < 2000?
- True → run the blockgrow savings, count a month
- Jump back to the checkthe condition is tested again
- False → leave the loopcontinue with print()
The condition is checked before every pass. If it is false at the start, the body never runs at all.
Common mistake: the infinite loop
If nothing inside the loop ever makes the condition false, the loop runs forever. Forgetting months += 1 or i += 1 is the classic cause. Press Ctrl+C in the terminal to stop a runaway program.
break: stop the loop now
break exits the nearest loop immediately, skipping any remaining items:
orders = [250, 480, -1, 300]
for amount in orders:
if amount < 0:
print("Invalid order found, stopping.")
break
print("Processing", amount)
Processing 250 Processing 480 Invalid order found, stopping.
continue: skip to the next pass
continue abandons the current pass and jumps back to the top of the loop:
for n in range(1, 11):
if n % 3 == 0:
continue # skip multiples of 3
print(n, end=" ")
1 2 4 5 7 8 10
The while True pattern
When the stop decision is made in the middle of the loop – typically after reading input – write an endless loop and break out of it:
PIN = "4321"
attempts = 0
while True:
entered = input("Enter PIN: ")
attempts += 1
if entered == PIN:
print("Unlocked!")
break
if attempts == 3:
print("Card blocked.")
break
print("Wrong PIN, try again.")
Enter PIN: 1111 Wrong PIN, try again. Enter PIN: 4321 Unlocked!
Loop else: "finished without break"
Both for and while can have an else block. It runs only if the loop ended normally – that is, without hitting break. It is perfect for searches:
def check_prime(n):
for d in range(2, int(n ** 0.5) + 1):
if n % d == 0:
print(f"{n} is not prime ({d} x {n // d})")
break
else:
print(f"{n} is prime")
check_prime(91)
check_prime(97)
91 is not prime (7 x 13) 97 is prime
Think of it as "no break". Many developers rarely use it, so add a short comment when you do.
for or while?
| Use for when… | Use while when… |
|---|---|
| you loop over a known collection or range | you repeat until a condition changes |
| the number of passes is known in advance | the number of passes depends on input or calculation |
| e.g. every student, every line of a file | e.g. retry until success, game loops, menus |
Real example: digits of a number
n = 90517
reversed_n = 0
digit_sum = 0
while n > 0:
digit = n % 10
digit_sum += digit
reversed_n = reversed_n * 10 + digit
n //= 10
print("Sum of digits:", digit_sum)
print("Reversed:", reversed_n)
Sum of digits: 22 Reversed: 71509
Practice
Try it yourself
Find the first power of 2 that is greater than 1,000.
Show solution
power = 1 while power <= 1000: power *= 2 print(power)1024
Print the Collatz sequence for 6: if even halve it, if odd multiply by 3 and add 1, until you reach 1.
Show solution
n = 6 steps = [n] while n != 1: n = n // 2 if n % 2 == 0 else 3 * n + 1 steps.append(n) print(steps)[6, 3, 10, 5, 16, 8, 4, 2, 1]
Quick check
What is the difference between break and continue?
break leaves the loop completely; continue skips the rest of the current pass and starts the next one.
When does a loop's else block run?
When the loop finishes without a break.
How many times does while False: print("x") print?
Zero – the condition is checked before the first pass.
Summary
while condition:repeats as long as the condition is true; make sure something changes it.breakexits the loop;continuejumps to the next pass.while True+breaksuits input loops; loopelsemeans "finished without break".
Finished this lesson?
Mark it complete to track your progress, then carry on with the next lesson.