Beginner
The while Loop, break, and continue
📂 Phase 2: Loops, Conditional Statements, Functions (Days 6–10) · Python ProgrammingA while loop repeats a block of code for as long as a condition stays true. Unlike a for loop, you don't know in advance how many times it will run — it depends entirely on when the condition becomes false.
Basic while Loop
count = 0
while count < 5:
print(count)
count += 1
# 0 1 2 3 4
You must update the loop variable yourself inside the body. Forgetting count += 1 here would create an infinite loop, since the condition would never become false.
while True — An Intentional Infinite Loop
Sometimes you genuinely want a loop to run forever until something inside it explicitly stops it — common in menu-driven programs or servers.
while True:
answer = input("Type 'quit' to exit: ")
if answer == "quit":
break
print(f"You typed: {answer}")
The break Statement
break exits the loop immediately and completely — execution jumps straight to the first line after the loop, skipping any remaining iterations entirely.
for n in range(1, 20):
if n == 8:
break
print(n)
# Prints 1 through 7, then stops the moment n equals 8
The continue Statement
continue skips only the rest of the current iteration and immediately moves to the next one — the loop itself keeps running.
for n in range(1, 10):
if n % 2 == 0:
continue # skip even numbers
print(n)
# Prints only the odd numbers: 1 3 5 7 9
break vs continue — Side by Side
| Statement | Effect | Remaining Iterations? |
|---|---|---|
| break | Exits the loop entirely | None — loop stops completely |
| continue | Skips just the current iteration | Yes — loop continues to the next item |
break and continue Inside a while Loop
num = 0
while num < 10:
num += 1
if num % 2 == 0:
continue # skip printing even numbers
if num == 9:
break # stop entirely once we reach 9
print(num)
# Prints: 1 3 5 7
The while-else Clause
Just like for-else, a while loop's else block runs only if the loop finished normally — without being interrupted by a break.
attempts = 0
max_attempts = 3
while attempts < max_attempts:
password = input("Enter password: ")
if password == "secret":
print("Access granted")
break
attempts += 1
else:
print("Too many failed attempts — locked out")
Interview tip: A frequently asked trick question is "Does the else block run if the loop never executes at all (e.g. the condition is false from the very start)?" — Yes. Since no break occurred, the else block still runs even if the loop body executed zero times.