🔄 While Loops
While loops are Python's most fundamental looping construct. They repeat a block of code as long as a specified condition remains true. Think of while loops as "keep doing this until something changes" - they're perfect for situations where you don't know exactly how many times you need to repeat an action.
While loops are essential for user input validation, waiting for events, processing data until a condition is met, and creating interactive programs that respond to changing conditions using decision-making concepts.
# Basic while loop
count = 1
while count <= 5:
print(f"Count: {count}")
count += 1 # Important: update the condition variable
print("Loop finished!")
📝 Basic While Loop Syntax
A while loop consists of the while
keyword, followed by a condition, a colon, and an indented code block. The condition is checked before each iteration, and the loop continues as long as the condition evaluates to True.
The most critical aspect of while loops is ensuring the condition eventually becomes False. Otherwise, you'll create an infinite loop that runs forever.
# Basic countdown example
countdown = 5
while countdown > 0:
print(f"T-minus {countdown}")
countdown -= 1 # This change makes the condition eventually False
print("Blast off!")
🎛️ Loop Control Variables
While loops typically use control variables that change during each iteration. These variables determine when the loop should stop and help track the loop's progress.
Properly managing control variables is crucial for loop correctness and preventing infinite loops or premature termination.
# Different control variable patterns
print("=== COUNTER VARIABLE ===")
i = 1
while i <= 3:
print(f"Iteration: {i}")
i += 1
print("\n=== BOOLEAN FLAG ===")
found = False
numbers = [1, 3, 5, 8, 9]
index = 0
while not found and index < len(numbers):
if numbers[index] % 2 == 0:
print(f"Found even number: {numbers[index]}")
found = True
index += 1
print("\n=== ACCUMULATOR VARIABLE ===")
total = 0
i = 1
while i <= 5:
total += i
i += 1
print(f"Sum of 1-5: {total}")
🔄 Quick While Loop Practice
Let's practice writing while loops that calculate results!
Hands-on Exercise
Write a while loop to calculate the sum of numbers from 1 to 10.
# 10 While Loop Practice - Calculate sum of 1 to
total = 0
count = 1
# 10 TODO: Your code here: write a while loop that adds numbers 1 through
# The final result should be stored in 'total'
Solution and Explanation 💡
Click to see the complete solution
# While Loop Practice - Solution
total = 0
count = 1
while count <= 10:
total += count
count += 1
print(f"Sum of 1 to 10: {total}")
Key Learning Points:
- 📌 Accumulator pattern: Use one variable to collect results (total)
- 📌 Counter variable: Use another variable to track iterations (count)
- 📌 Two updates: Update both accumulator and counter in each iteration
- 📌 Final result: The loop builds up the answer step by step
🛡️ Input Validation with While Loops
One of the most common uses for while loops is input validation. They allow you to repeatedly ask users for input until they provide valid data, creating robust and user-friendly programs.
Input validation loops improve user experience by giving users multiple chances to provide correct input rather than crashing or accepting invalid data.
# Age validation with error handling
print("=== AGE VALIDATION ===")
valid_age = False
while not valid_age:
try:
age_input = "25" # Simulated user input (normally input() function)
age = int(age_input)
if 0 <= age <= 120:
valid_age = True
print(f"Your age is: {age}")
else:
print("Age must be between 0 and 120")
# In real code, this would continue asking for input
break # Breaking for demo purposes
except ValueError:
print("Please enter a valid number")
# In real code, this would continue asking for input
break # Breaking for demo purposes
print("\n=== MENU VALIDATION ===")
valid_choice = False
while not valid_choice:
print("Choose an option:")
print("1. Save")
print("2. Load")
print("3. Quit")
choice = "2" # Simulated user input
if choice in ["1", "2", "3"]:
valid_choice = True
options = {"1": "Save", "2": "Load", "3": "Quit"}
print(f"You selected: {options[choice]}")
else:
print("Invalid choice. Please enter 1, 2, or 3.")
break # Breaking for demo purposes
📊 Common While Loop Patterns
There are several patterns you'll use frequently when working with while loops in different programming scenarios.
Pattern | Example | Use Case |
---|---|---|
Counter Loop | while count < 10: | Fixed number of iterations |
Infinite Loop + Break | while True: ... break | Input validation |
Flag-Controlled | while not done: | Event-driven processing |
Sentinel Value | while value != -1: | Process until special value |
List Processing | while items: | Process until collection empty |
# Common while loop patterns
print("=== COUNTER PATTERN ===")
count = 0
while count < 3:
print(f"Count: {count}")
count += 1
print("\n=== INFINITE LOOP + BREAK PATTERN ===")
attempt = 0
while True:
attempt += 1
password = "secret" if attempt == 2 else "wrong" # Simulated input
if password == "secret":
print("Access granted!")
break
elif attempt >= 3:
print("Too many attempts!")
break
else:
print(f"Wrong password. Attempt {attempt}/3")
print("\n=== FLAG-CONTROLLED PATTERN ===")
processing = True
items_processed = 0
while processing:
items_processed += 1
print(f"Processing item {items_processed}")
if items_processed >= 3: # Stop condition
processing = False
print("\n=== LIST PROCESSING PATTERN ===")
items = ["apple", "banana", "cherry"]
while items:
item = items.pop(0) # Remove first item
print(f"Processing: {item}")
⚡ Loop Control with Break and Continue
While loops can be controlled using break
and continue
statements, providing fine-grained control over loop execution flow.
These control statements work with conditional logic to create sophisticated loop behavior.
# Loop control examples
print("=== BREAK EXAMPLE ===")
i = 0
while i < 10:
i += 1
if i == 2:
continue # Skip when i is 2
if i == 5:
break # Exit when i is 5
print(i)
print("\n=== WHILE-ELSE EXAMPLE ===")
# Using else with while loop
target = 7
num = 1
while num <= 5:
if num == target:
print(f"Found {target}!")
break
num += 1
else:
print(f"{target} not found") # Executes because loop completed normally
✅ While Loop Best Practices
Following best practices helps you write efficient, readable, and maintainable while loops.
📚 Key Takeaways
Test Your Knowledge
Test what you've learned about while loops in Python:
🚀 What's Next?
Congratulations! You now understand while loops and can create condition-based repetition in your Python programs. While loops are perfect for situations where you don't know exactly how many iterations you need.
Next, you'll learn about For Loops, which are designed for iterating through sequences and collections. For loops complement while loops by providing an elegant way to process lists, strings, and other iterable data structures.
While loops work hand-in-hand with input validation, decision making, and data processing scenarios.
Understanding while loops prepares you for advanced loop techniques, function development, and error handling.
Was this helpful?
Track Your Learning Progress
Sign in to bookmark tutorials and keep track of your learning journey.
Your progress is saved automatically as you read.