The while Loop
Overview
The while loop repeats as long as a condition remains true. You'll learn to use it for indefinite repetition, track counters, and prevent infinite loops with proper control statements.
What You Will Learn in This Lesson
By the end of this lesson, you will know:
- What a while loop is: Understand how while loops repeat code as long as a condition is True.
- How while loops work: Learn the step-by-step process of how Python evaluates and executes while loops.
- Using counters: Master how to track progress and control loop execution with counters.
- Preventing infinite loops: Learn how to ensure your loops eventually stop.
Why This Matters
The while loop is perfect for situations where you don't know exactly how many times you need to repeat code. It keeps running until a condition becomes False. This is essential for user input validation, game loops, and any situation where you need to repeat until something changes.
Step 1: What Is a while Loop?
A while loop repeats code as long as a condition is True. Think of it like a question: "While this is true, keep doing that." It's different from a for loop because you don't know exactly how many times it will run - it depends on when the condition becomes False.
while condition:
# Code to repeat
print("This runs while condition is True")
# More code here
Start with while
The keyword while tells Python you're starting a loop that repeats based on a condition.
Write the Condition
After while, write a condition that evaluates to True or False. This can be a comparison, a boolean variable, or a logical expression.
Add a Colon
End the condition line with a colon :. This tells Python that the code block is coming next.
Indent the Code Block
All code that should run when the condition is True must be indented. Python uses indentation to know what belongs to the while loop.
Key Difference: Unlike a for loop, a while loop doesn't automatically stop after a certain number of times. It keeps running until the condition becomes False. This makes it powerful but also potentially dangerous - if the condition never becomes False, you'll get an infinite loop!
Mini Practice #1: Your First while Loop
Try It YourselfTry this simple while loop that counts from 1 to 5:
What happened? Python first checked the condition: count <= 5. Since count is 1, and 1 is less than or equal to 5, the condition was True, so Python entered the loop and printed "Count: 1". Then it increased count by 1 (using count = count + 1), making count equal to 2. Python then checked the condition again. Since 2 <= 5 is still True, it printed "Count: 2" and increased count again. This process repeated until count became 6. When Python checked 6 <= 5, it was False, so the loop stopped and Python printed "Done!". Notice how the counter (count) changes each time through the loop, eventually making the condition False.
Step 2: How while Loops Work
Python evaluates the condition before each iteration (each time through the loop). If the condition is True, Python runs all the indented code. After running the code, Python checks the condition again. If it's still True, the loop runs again. This continues until the condition becomes False.
When Condition Is True
Python runs all indented code, then checks the condition again.
count = 1
while count <= 3:
print(count)
count = count + 1
Output: 1
2
3
Loop runs 3 times
When Condition Is False
Python skips the entire while block and continues with the next line.
count = 10
while count <= 3:
print(count)
count = count + 1
print("Skipped")
Output: Skipped
Loop never runs
Execution Flow
Here's exactly what Python does:
- Check the condition. If False, skip to step 4.
- If True, run all indented code inside the loop.
- Go back to step 1 (check the condition again).
- Continue with the next non-indented line after the loop.
This creates a cycle: check condition → run code → check condition → run code → ... until the condition becomes False.
Step 3: Using Counters
One of the most common patterns with while loops is using a counter variable. A counter keeps track of how many times the loop has run or tracks progress toward a goal. You initialize it before the loop, check it in the condition, and update it inside the loop.
# 1. Initialize counter before the loop
count = 0
# 2. Check counter in the while condition
while count < 5:
# 3. Do something
print(f"Loop iteration: {count}")
# 4. Update counter inside the loop
count = count + 1
Initialize the Counter
Create a variable before the loop and set it to a starting value (usually 0 or 1).
count = 0
Use Counter in Condition
Write a condition that checks the counter value. When the counter reaches a certain value, the condition becomes False.
while count < 5:
Update Counter Inside Loop
Inside the loop, change the counter value so it moves toward making the condition False. Without this, you'd have an infinite loop!
count = count + 1
Critical: You MUST update the counter inside the loop. If you forget to change the counter, the condition will always be True and your loop will run forever (an infinite loop). This is one of the most common mistakes beginners make!
Mini Practice #2: Counting with a Counter
Try It YourselfTry this example that uses a counter to sum numbers:
What happened? This code adds up the numbers from 1 to 5. The variable total starts at 0 and accumulates the sum. The variable count starts at 1 and goes up by 1 each time through the loop. Each iteration, the code adds the current value of count to total, then increases count by 1. When count becomes 6, the condition count <= 5 becomes False, so the loop stops. The final total is 15 (1+2+3+4+5). This pattern of accumulating values is very common in programming!
Step 4: Preventing Infinite Loops
An infinite loop runs forever because the condition never becomes False. This is a serious problem - your program will freeze and become unresponsive. Always make sure something inside your loop changes a value that affects the condition.
✅ Safe Loop (Stops)
The counter is updated, so the loop eventually stops:
count = 1
while count <= 5:
print(count)
count = count + 1 # Counter changes!
This will stop after 5 iterations
❌ Infinite Loop (Danger!)
The counter is never updated, so the condition stays True forever:
count = 1
while count <= 5:
print(count)
# Missing: count = count + 1
This runs forever!
How to Avoid Infinite Loops
Before writing a while loop, ask yourself:
- What makes the condition True initially?
- What will make the condition False eventually?
- Is there code inside the loop that changes a value affecting the condition?
If you can't answer these questions, your loop might run forever. Always ensure something inside the loop moves toward making the condition False.
Step 5: Real-World Example
Here's a practical example of using a while loop in a real program:
# Countdown timer
seconds = 10
while seconds > 0:
print(f"Time remaining: {seconds} seconds")
seconds = seconds - 1
print("Time's up!")
How This Works
This creates a countdown timer that starts at 10 and counts down to 1. Each time through the loop, it prints the remaining time and decreases seconds by 1. When seconds becomes 0, the condition seconds > 0 becomes False, so the loop stops and "Time's up!" is printed. This is a common pattern for timers, games, and any situation where you need to count down or track progress.
End-of-Lesson Exercises
Exercise 1: Write a while Loop
Create a variable count = 1. Write a while loop that prints count as long as count <= 3, then increases count by 1 each time.
Use while count <= 3: followed by a print statement and count = count + 1.
Exercise 2: Sum with while Loop
Create variables: total = 0 and count = 1. Use a while loop to add numbers from 1 to 5 to total. Print the final total.
Use while count <= 5:, add count to total, then increase count by 1.