Python While Loops
Python While Loops: Mastering break, continue, and else
A while loop in Python repeatedly executes a block of code as long as a given condition evaluates to True. Unlike for loops, which iterate over a sequence, while loops are condition-driven and run until that condition becomes False.
1. Basic while Loop Syntax
count = 1
while count <= 5:
print(f"Count is: {count}")
count += 1
- How it works: Before each iteration, Python checks if
count <= 5. If true, the code inside runs. If false, the loop terminates. Always ensure your loop variable updates so you don't accidentally create an infinite loop.
Advertisement
2. Controlling Loops: break and continue
Python provides flow control statements to alter how loops execute:
The break Statement
The break statement immediately exits the loop entirely, bypassing any remaining code and the loop's condition check.
# Stop searching when the target number is found
number = 1
while number <= 10:
if number == 7:
print("Target found! Breaking out of loop.")
break
print(f"Checking number: {number}")
number += 1
The continue Statement
The continue statement skips the rest of the code inside the current iteration and jumps straight back to the loop's condition evaluation for the next cycle.
# Skip printing even numbers
num = 0
while num < 5:
num += 1
if num % 2 == 0:
continue # Skips the print statement for even numbers
print(f"Odd number: {num}")
Advertisement
3. The Unique else Clause in Python Loops
One of Python's unique features is the ability to attach an else block to a while (or for) loop.
- When does it run? The
elseblock executes only when thewhileloop condition becomesFalsenaturally. - When does it NOT run? If the loop is terminated early via a
breakstatement, theelseblock is skipped entirely.
attempts = 3
while attempts > 0:
password = input("Enter password: ")
if password == "secret123":
print("Access granted!")
break
attempts -= 1
else:
# This triggers ONLY if the loop finishes without hitting the 'break'
print("Access denied! Too many failed attempts.")