Introduction
In previous lessons you used for loops to iterate over sequences in a predictable, countable way. In this lesson, you’ll learn how to use while loops to repeat actions as long as a condition stays true, and how to control those loops precisely with break and continue. You’ll also see common patterns with counters, sentinels, and flags that appear in real-world programs.
By the end, you’ll be able to design safe while loops (avoiding infinite loops), exit them early when needed, skip specific iterations, and combine them with state variables for flexible control flow.
The while Loop: Repeating While a Condition Is True
A while loop repeatedly executes its body while a Boolean condition remains true.
General form:
while condition:
# loop body
# runs again if condition is still True
The condition is checked before each iteration. When it becomes False, the loop stops.
Example: Simple Counter with while
counter = 1
while counter <= 5:
print("Counter:", counter)
counter += 1
# Output:
# Counter: 1
# Counter: 2
# Counter: 3
# Counter: 4
# Counter: 5
Explanation:
- Initialization:
counter = 1 - Condition:
counter <= 5 - Update:
counter += 1moves the loop toward termination.
When counter becomes 6, the condition is False, so the loop stops.
Designing Safe while Loops (Avoiding Infinite Loops)
A safe while loop always has these three elements:
- Initialization – set up variables before the loop.
- Condition – a Boolean expression that can eventually become
False. - Update – change variables inside the loop so the condition will eventually be
False.
If the condition never becomes False, you get an infinite loop.
Example: Loop With Missing Update (Infinite Loop Bug)
n = 0
while n < 3:
print("n is", n)
# BUG: missing update like n += 1
This will print forever because n stays 0, so n < 3 is always True.
Fixed Version
n = 0
while n < 3:
print("n is", n)
n += 1
# Output:
# n is 0
# n is 1
# n is 2
Always double-check that your loop variables change in a way that can make the condition false.
Exiting Early with break
Sometimes you want to stop a loop even if the condition is still true. Use break to exit the loop immediately.
Example: Search Until Found (Using break)
secret = 27
guess = 0
while guess <= 100:
if guess == secret:
print("Found it!", guess)
break
guess += 1
else:
# This else runs only if the while loop ends normally (no break)
print("Secret not found in range.")
# Output:
# Found it! 27
Explanation:
- The loop counts from 0 up to 100.
- When
guess == secret, it prints and executesbreak. breakimmediately stops thewhileloop; theelseblock is skipped.
Using break is common in search problems: continue looping while scanning data, then exit as soon as you find the target.
Skipping Iterations with continue
continue skips the rest of the loop body for the current iteration and jumps back to the condition check.
Example: Print Only Odd Numbers with continue
n = 0
while n < 10:
n += 1
if n % 2 == 0:
# Skip even numbers
continue
print("Odd:", n)
# Output:
# Odd: 1
# Odd: 3
# Odd: 5
# Odd: 7
# Odd: 9
Explanation:
- The counter is updated first:
n += 1. - If
nis even,continueruns and theprintis skipped. - The loop then proceeds to the next iteration.
A common mistake is to put the update after the continue, which can cause infinite loops. Always ensure your update executes regardless of continue, or design the flow so it cannot be skipped accidentally.
Using Counters in while Loops
Counters are very common with while when you need flexible stopping logic.
Example: Retry with Maximum Attempts
max_attempts = 3
attempt = 0
password = "python123"
while attempt < max_attempts:
user_input = input("Enter password: ")
attempt += 1
if user_input == password:
print("Access granted.")
break
else:
print("Incorrect password.")
if attempt == max_attempts and user_input != password:
print("Too many attempts. Access denied.")
# Example Output (user enters wrong twice, then correct):
# Enter password: test
# Incorrect password.
# Enter password: hello
# Incorrect password.
# Enter password: python123
# Access granted.
Explanation:
attemptcounts how many times the user has tried.- Condition ensures we never exceed
max_attempts. breakexits early on success, even if attempts remain.
Sentinel-Controlled while Loops
A sentinel is a special value that means “stop now”. You loop until the user (or data) produces that value.
Example: Sum Numbers Until User Enters 0 (Sentinel)
total = 0
print("Enter numbers to sum (0 to finish):")
while True:
value = int(input("> "))
if value == 0: # 0 is the sentinel
break
total += value
print("Total:", total)
# Example Output:
# Enter numbers to sum (0 to finish):
# > 10
# > 5
# > -3
# > 0
# Total: 12
Explanation:
- Uses an infinite
while Trueloop plus a sentinel (0) to decide when tobreak. - As long as the value is not the sentinel, we add it to
total.
This pattern is powerful when you don’t know how many items will arrive.
Flag-Controlled while Loops
A flag is a Boolean variable that represents some state, such as running = True. You update the flag in the loop to decide when to stop.
Example: Menu Loop with Flag
running = True
while running:
print("\nMenu:")
print("1. Say hello")
print("2. Say goodbye")
print("3. Exit")
choice = input("Choose an option (1-3): ")
if choice == "1":
print("Hello!")
elif choice == "2":
print("Goodbye!")
elif choice == "3":
print("Exiting program...")
running = False # update flag to stop loop
else:
print("Invalid choice. Try again.")
# Example Output (user chooses 1, then 3):
# Menu:
# 1. Say hello
# 2. Say goodbye
# 3. Exit
# Choose an option (1-3): 1
# Hello!
#
# Menu:
# 1. Say hello
# 2. Say goodbye
# 3. Exit
# Choose an option (1-3): 3
# Exiting program...
Explanation:
runningstarts asTrueand keeps the loop going.- When the user chooses 3, we set
running = False, so the next condition check fails and the loop ends.
Flag-controlled loops are useful when multiple conditions can stop the loop, not just one counter or one sentinel value.
Combining Patterns: Counter + Flag + break
In real programs you often mix these techniques.
Example: Limited-Guess Number Game
secret = 15
max_guesses = 5
attempt = 0
won = False
while attempt < max_guesses and not won:
guess = int(input("Guess the number (1-20): "))
attempt += 1
if guess == secret:
print("Correct! You won in", attempt, "guesses.")
won = True
elif guess < secret:
print("Too low.")
else:
print("Too high.")
if not won:
print("Out of guesses. The number was", secret)
# Example Output:
# Guess the number (1-20): 10
# Too low.
# Guess the number (1-20): 18
# Too high.
# Guess the number (1-20): 15
# Correct! You won in 3 guesses.
Explanation:
- Counter:
attemptlimited bymax_guesses. - Flag:
wonshows if the user guessed correctly. - Loop condition combines both: keep going only while attempts remain and the user hasn’t won.
Summary / Key Takeaways
In this lesson on while Loops and Loop Control Statements, you have learned:
whileloops repeat based on conditions: They continue running as long as their Boolean condition evaluates toTrue, making them ideal for open-ended or state-driven repetition.- Safe loop design needs three parts: Proper initialization, a condition that can become
False, and reliable updates in the loop body help prevent infinite loops. breakexits loops early: You can terminate awhileloop immediately when a target condition is met, such as finding a desired value.continueskips specific iterations: It ignores the remaining statements in the current iteration while still allowing subsequent iterations to run.- Counters support bounded repetition: Using numeric counters with
whileenables retry limits, bounded attempts, and controlled counting behavior. - Sentinel values signal termination: Special input or data values (like
0or"quit") can be used withwhile Trueplusbreakto stop reading when the sentinel appears. - Flags represent loop state: Boolean flags like
runningorfinishedlet you stop loops based on complex or multiple conditions. - Patterns can be combined: Practical programs often mix counters, sentinels, flags,
break, andcontinueto build flexible, robust iteration logic.
