Python while Loop — Precise Guide with Tips & Tricks
Syntax, rules, break, continue, else, nested loops, and what never to get wrong
■ What is a while Loop?
A while loop keeps repeating a block of code as long as a condition is True. The moment the condition becomes False, the loop stops and Python
moves on.
Use while when you do not know in advance how many times the loop will run — for example, keep asking until the user types the right answer.
while condition:
# block runs repeatedly while condition is True
■ Three things must happen: 1) condition checked, 2) block runs if True, 3) something inside must eventually make the condition False —
otherwise it loops forever.
01 Syntax & Core Rules
while condition:
# indented body
# something here must change the condition
Rules that must never be broken:
1. Colon : after the condition is mandatory.
2. The body must be indented — 4 spaces or 1 Tab.
3. Something inside the loop must change the condition or use break — otherwise infinite loop.
4. The condition is checked before every iteration. If False from the start, the body never runs even once.
Basic example — count 1 to 5:
i = 1
while i <= 5:
print(i)
i += 1 # THIS IS CRITICAL — updates i each time
>> 1
>> 2
>> 3
>> 4
>> 5
# Step by step: i=1 (True, print 1, i=2), i=2 (True, print 2, i=3) ... i=6 (False, stop)
■ Forgetting i += 1 (or whatever updates the condition) creates an INFINITE LOOP. The program freezes. Press Ctrl+C in the terminal to force-stop
it.
02 Infinite Loop — while True
while True: is an intentional infinite loop. It runs forever on purpose. You control when it stops using break inside the body.
while True:
answer = input('Type quit to stop: ')
if answer == 'quit':
break # exits the loop immediately
print(f'You typed: {answer}')
>> Type quit to stop: hello
>> You typed: hello
>> Type quit to stop: quit
# Loop ends here — program continues after the while block
★ while True + break is the standard pattern when you want to keep looping until a user does something specific. Very commonly used
for menus and input validation.
03 break — Exit the Loop Immediately
break stops the loop right away, no matter what the condition says. Python jumps out and continues with the code after the loop.
i = 1
while i <= 10:
if i == 5:
break # stop as soon as i reaches 5
print(i)
i += 1
>> 1
>> 2
>> 3
>> 4
# 5 is never printed — break fired before print
Practical use — stop when correct password entered:
while True:
pw = input('Password: ')
if pw == 'python99':
print('Access granted.')
break
print('Wrong. Try again.')
>> Password: hello
>> Wrong. Try again.
>> Password: python99
>> Access granted.
■ break only exits the loop it is directly inside. If loops are nested, break only exits the inner loop.
04 continue — Skip This Iteration, Keep Looping
continue skips the rest of the current iteration and jumps straight back to the condition check. The loop does NOT stop — it just skips that one pass.
i = 0
while i < 6:
i += 1
if i == 3:
continue # skip printing when i is 3
print(i)
>> 1
>> 2
# 3 is skipped
>> 4
>> 5
>> 6
Practical use — skip invalid input, keep asking:
while True:
val = input('Enter a number: ')
if not [Link]():
print('Numbers only!')
continue # go back, ask again
print(f'You entered: {int(val)}')
break
>> Enter a number: abc
>> Numbers only!
>> Enter a number: 42
>> You entered: 42
★ break = exit the loop entirely. continue = skip this round, keep going. They are opposites in behaviour.
■ With continue, make sure the variable that controls the condition is updated BEFORE the continue line — otherwise infinite loop.
05 while...else — The Forgotten Feature
A while loop can have an else block. The else runs only when the condition becomes False naturally — it does NOT run if the loop was stopped
by break.
while condition:
# loop body
else:
# runs only if loop ended normally (not by break)
Example — search for a number:
target = 7
i = 1
while i <= 5:
if i == target:
print(f'Found {target}!')
break
i += 1
else:
print('Not found in range.')
>> Not found in range.
# target=7 is not in 1-5, so loop ended normally, else ran
■ else after while is rare but powerful. It tells you: the loop finished without being interrupted by break.
06 Common while Loop Patterns
Pattern 1 — Counter (count up):
i = 1
while i <= 5:
print(f'Count: {i}')
i += 1
>> Count: 1 ... Count: 5
Pattern 2 — Counter (count down):
i = 5
while i >= 1:
print(f'T-minus {i}')
i -= 1
print('Liftoff!')
>> T-minus 5 ... T-minus 1
>> Liftoff!
Pattern 3 — Running total (sum of inputs):
total = 0
count = 0
while count < 3:
num = int(input(f'Enter number {count+1}: '))
total += num
count += 1
print(f'Total: {total}')
>> Enter number 1: 10
>> Enter number 2: 25
>> Enter number 3: 15
>> Total: 50
Pattern 4 — Keep asking until valid (input guard):
age = -1
while age < 0 or age > 120:
age = int(input('Enter valid age: '))
print(f'Age accepted: {age}')
>> Enter valid age: -5
>> Enter valid age: 200
>> Enter valid age: 25
>> Age accepted: 25
Pattern 5 — Accumulate into a list:
items = []
while True:
name = input('Enter item (or done): ').strip()
if [Link]() == 'done':
break
[Link](name)
print(items)
>> Enter item (or done): Apple
>> Enter item (or done): Mango
>> Enter item (or done): done
>> ['Apple', 'Mango']
07 Nested while Loops
A while loop placed inside another while loop. The inner loop completes all its iterations for every single iteration of the outer loop.
i = 1
while i <= 3:
j = 1
while j <= 3:
print(f' {i} x {j} = {i*j}')
j += 1
i += 1
>> 1 x 1 = 1 | 1 x 2 = 2 | 1 x 3 = 3
>> 2 x 1 = 2 | 2 x 2 = 4 | 2 x 3 = 6
>> 3 x 1 = 3 | 3 x 2 = 6 | 3 x 3 = 9
■ Each loop needs its OWN counter variable (i and j). Using the same variable for both loops causes chaos.
★ break inside a nested loop only exits the INNER loop. The outer loop keeps running.
08 Common Mistakes — And How to Fix Them
Mistake 1 — Forgetting to update the counter → infinite loop:
i = 1
while i <= 5:
print(i) # i never changes — loops forever!
i = 1
while i <= 5:
print(i)
i += 1 # CORRECT — always update
Mistake 2 — Missing colon:
while i < 5 # SyntaxError — colon is missing
while i < 5: # CORRECT
Mistake 3 — Wrong indentation:
while i < 5:
print(i) # IndentationError — not indented
while i < 5:
print(i) # CORRECT
Mistake 4 — continue before updating counter → infinite loop:
while i <= 5:
if i == 3:
continue # i is never updated when i==3, loops forever
print(i)
i += 1
while i <= 5:
i += 1 # CORRECT — update BEFORE continue
if i == 3:
continue
print(i)
Mistake 5 — Condition never becomes False:
i = 1
while i > 0: # i starts at 1, always > 0, never stops
print(i)
i += 1
while i > 0:
print(i)
i -= 1 # CORRECT — decrease so it eventually hits 0
09 Tips & Tricks — Burn These Into Memory
★ Every while loop needs something that changes — a counter, a variable, or a break. No change = infinite loop.
★ while True + break is your best friend for menus, login systems, and input validation. Learn this pattern well.
★ break exits the loop completely. continue skips only the current round. Know the difference.
★ The condition is checked BEFORE the body runs. If it is False from the start, the body never executes even once.
★ Press Ctrl+C in the terminal to stop an accidentally infinite loop. Do not panic — just press it.
★ In nested loops, break only exits the innermost loop. Each loop needs its own counter variable.
★ while...else is rare but useful: the else runs only if the loop ended naturally, not by break.
★ Use while for unknown number of repetitions (user input, searching). Use for when you know the count.
★ Always initialise your counter BEFORE the loop: i = 0, then while i < 5. Never inside.
★ With continue, always update your counter BEFORE the continue line — or you will loop forever on the same value.
■ Quick Reference — while Loop at a Glance
Feature Code Pattern Purpose
Basic while while i < 5: ... i += 1 Repeat while condition True
Infinite loop while True: Loop forever until break
break if x == y: break Exit loop immediately
continue if x == y: continue Skip this round, keep looping
while...else while ...: ... else: ... else runs if no break fired
Count up i = 1 / while i <= n / i += 1 1, 2, 3 ... n
Count down i = n / while i >= 1 / i -= 1 n, n-1 ... 1
Input guard while True: ... if valid: break Keep asking until valid
Running total total = 0 / total += num Accumulate values
Nested loops while i: / while j: / j+=1 / i+=1 Each needs own counter
End of Guide — Happy Coding! ■