π Exercise Five: The While Loop
Executing a block of code over and over until a certain condition is met is one of the things that makes computer programming much easier than spreadsheeting for certain problems. The simplest, and most general form of this type of procedure, called a loop, is implemented in Python with the while statement.
- How to repeat code using
whileloops - How to control when a loop stops
- How to avoid infinite loops
- Common loop patterns and practical examples
Imagine you need to add up 1000 numbers, or print a message 50 times, or keep asking a user for input until they type "quit." Without loops, you'd have to write the same code over and over. Loops let you write it once and repeat it as many times as needed!
π 1. The while Construct
The while statement will look a lot like the if statementβit has a Boolean argument. The difference is that the while loop will keep executing the indented code inside until the Boolean statement becomes false.
Basic Structure
while condition:
# This indented code runs repeatedly
# as long as condition is True
# Don't forget to update variables!Your First While Loop
A = 0
while A < 5:
print(A)
A += 11
2
3
4
How Does This Work?
Let's trace through the loop step by step:
A = 0 β Variable A is initialized to 0
A < 5? Is 0 < 5? Yes (True) β Enter the loop
print(A) β Prints 0
A += 1 β A becomes 1
while and check again: Is 1 < 5? Yes β Continue...
Iteration Table
Here's what happens during each iteration:
| Iteration | Value of A (start) | Is A < 5? | Output | Value of A (end) |
|---|---|---|---|---|
| 1 | 0 | True | 0 | 1 |
| 2 | 1 | True | 1 | 2 |
| 3 | 2 | True | 2 | 3 |
| 4 | 3 | True | 3 | 4 |
| 5 | 4 | True | 4 | 5 |
| 6 | 5 | False | β | Loop exits |
Just like with if statements, the code inside a while loop must be indented. Python uses indentation to know which lines belong inside the loop. When you stop indenting, you're outside the loop.
βοΈ 2. while vs if: What's the Difference?
Both while and if use Boolean conditions, but they behave very differently:
| Feature | if Statement |
while Loop |
|---|---|---|
| Execution | Runs the code block once (if condition is true) | Runs the code block repeatedly (while condition is true) |
| Checking | Checks condition once | Checks condition before each iteration |
| Use Case | Make a decision | Repeat an action |
Side-by-Side Example
if (runs once):
x = 1
if x < 5:
print(x)
x += 1
print("Done")Done
while (repeats):
x = 1
while x < 5:
print(x)
x += 1
print("Done")2
3
4
Done
βΎοΈ 3. Infinite Loops
Intentional Infinite Loops
If you want the loop to run forever (called an infinite loop), you could just write:
while True:
print("Help me -- I can't stop!")True is always true, so Python will keep printing the message forever. You would need to manually stop the program (usually by pressing Ctrl+C or clicking the stop button in your IDE).
While intentional infinite loops have their uses (like game loops or servers that run continuously), most of the time you'll want your loops to eventually stop.
Unintentional Infinite Loops
Unintended infinite loops are common errors that new programmers often face. While they can generally be traced back to a logic error, the most common cause is that the programmer, in the indented sections of code, does not update variables used in the Boolean expression that controls whether or not the loop is executed.
Imagine what would happen if there were no A += 1 in our first loop:
# THIS IS BROKEN - DO NOT RUN!
A = 0
while A < 5:
print(A)
# Oops! We forgot A += 1
# A will ALWAYS be 0
# 0 < 5 will ALWAYS be True
# This prints 0 forever!Since A never changes, the condition A < 5 is always True, and the loop runs forever!
How to Stop a Runaway Program
If you accidentally create an infinite loop:
- In Spyder: Click the red square (stop) button or press Ctrl+C
- In the terminal: Press Ctrl+C
- In IDLE: Go to Shell β Restart Shell
π 4. Common While Loop Patterns
Pattern 1: Counting Up
# Count from 1 to 5
count = 1
while count <= 5:
print(count)
count += 12
3
4
5
Pattern 2: Counting Down
# Countdown from 5 to 1
count = 5
while count >= 1:
print(count)
count -= 1
print("Blastoff!")4
3
2
1
Blastoff!
Pattern 3: Accumulator (Running Total)
# Sum the numbers 1 through 5
total = 0
number = 1
while number <= 5:
total = total + number
print("Adding " + str(number) + ", total is now " + str(total))
number += 1
print("Final sum: " + str(total))Adding 2, total is now 3
Adding 3, total is now 6
Adding 4, total is now 10
Adding 5, total is now 15
Final sum: 15
Pattern 4: User-Controlled Loop (Sentinel Value)
Keep asking for input until the user types a specific value to quit:
# Keep asking until user types "quit"
user_input = ""
while user_input != "quit":
user_input = input("Enter a command (or 'quit' to exit): ")
if user_input != "quit":
print("You entered: " + user_input)
print("Goodbye!")You entered: hello
Enter a command (or 'quit' to exit): test
You entered: test
Enter a command (or 'quit' to exit): quit
Goodbye!
Pattern 5: Input Validation
Keep asking until the user provides valid input:
# Keep asking until user enters a positive number
number = -1
while number < 0:
number = int(input("Enter a positive number: "))
if number < 0:
print("That's not positive! Try again.")
print("Thank you! You entered: " + str(number))That's not positive! Try again.
Enter a positive number: -2
That's not positive! Try again.
Enter a positive number: 7
Thank you! You entered: 7
π― 5. Complete Examples
Example 1: Guessing Game
# Number guessing game
secret_number = 7
guess = 0
attempts = 0
print("=== Guess the Number ===")
print("I'm thinking of a number between 1 and 10")
print()
while guess != secret_number:
guess = int(input("Enter your guess: "))
attempts += 1
if guess < secret_number:
print("Too low! Try again.")
elif guess > secret_number:
print("Too high! Try again.")
else:
print("Correct!")
print()
print("You got it in " + str(attempts) + " attempts!")I'm thinking of a number between 1 and 10
Enter your guess: 5
Too low! Try again.
Enter your guess: 8
Too high! Try again.
Enter your guess: 7
Correct!
You got it in 3 attempts!
Example 2: Calculate Average
# Calculate average of numbers entered by user
print("=== Average Calculator ===")
print("Enter numbers to average. Type -1 to finish.")
print()
total = 0
count = 0
number = 0
while number != -1:
number = float(input("Enter a number (-1 to finish): "))
if number != -1:
total = total + number
count = count + 1
print()
if count > 0:
average = total / count
print("You entered " + str(count) + " numbers")
print("The sum is: " + str(total))
print("The average is: " + str(average))
else:
print("No numbers were entered.")Enter numbers to average. Type -1 to finish.
Enter a number (-1 to finish): 10
Enter a number (-1 to finish): 20
Enter a number (-1 to finish): 30
Enter a number (-1 to finish): -1
You entered 3 numbers
The sum is: 60.0
The average is: 20.0
Example 3: Multiplication Table
# Print multiplication table for a number
number = int(input("Enter a number for the multiplication table: "))
print()
print("=== Multiplication Table for " + str(number) + " ===")
print()
multiplier = 1
while multiplier <= 10:
result = number * multiplier
print(str(number) + " x " + str(multiplier) + " = " + str(result))
multiplier += 1=== Multiplication Table for 7 ===
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70
β οΈ Common Mistakes (And How to Fix Them)
Mistake 1: Forgetting to Update the Loop Variable
count = 1
while count <= 5:
print(count)
# Forgot to increment count!count = 1
while count <= 5:
print(count)
count += 1 # Don't forget this!Mistake 2: Wrong Initial Value
count = 10 # Starting too high!
while count < 5:
print(count)
count += 1
# 10 < 5 is False, so loop body never executescount = 1 # Start at appropriate value
while count < 5:
print(count)
count += 1Mistake 3: Off-by-One Errors
count = 1
while count < 5: # Should be <= 5
print(count)
count += 1count = 1
while count <= 5: # Use <= to include 5
print(count)
count += 1Mistake 4: Updating Variable Outside the Loop
count = 1
while count <= 5:
print(count)
count += 1 # This is OUTSIDE the loop (not indented!)count = 1
while count <= 5:
print(count)
count += 1 # This is INSIDE the loop (indented)Mistake 5: Forgetting the Colon
count = 1
while count <= 5 # ERROR! Missing colon
print(count)
count += 1count = 1
while count <= 5: # Don't forget the colon!
print(count)
count += 1πͺ Practice Exercises
Try writing these programs on your own!
Exercise 1: Print Even Numbers
Write a program that prints all even numbers from 2 to 20.
Expected output: 2, 4, 6, 8, 10, 12, 14, 16, 18, 20
Hint: Start at 2 and add 2 each time, OR start at 1 and use an if statement to check if the number is even.
Exercise 2: Sum of Numbers
Write a program that:
- Asks the user for a positive integer N
- Calculates the sum of all integers from 1 to N
- Displays the result
Example: If N = 5, output should be 15 (because 1+2+3+4+5 = 15)
Exercise 3: Factorial Calculator
Write a program that calculates the factorial of a number:
- Asks the user for a non-negative integer
- Calculates N! (N factorial = N Γ (N-1) Γ (N-2) Γ ... Γ 1)
- Displays the result
Example: 5! = 5 Γ 4 Γ 3 Γ 2 Γ 1 = 120
Exercise 4: Password Checker
Write a program that:
- Has a secret password stored in a variable
- Keeps asking the user to enter the password
- Gives them a maximum of 3 attempts
- Prints "Access granted!" if correct, or "Account locked!" after 3 failed attempts
Exercise 5: Powers of Two
Write a program that prints all powers of 2 that are less than 1000:
Expected output: 1, 2, 4, 8, 16, 32, 64, 128, 256, 512
Hint: Start with 1 and keep multiplying by 2.
Exercise 6: Number Reverser
Write a program that reverses a positive integer:
- Asks for a positive integer
- Reverses its digits
- Displays the reversed number
Example: Input: 12345 β Output: 54321
Hint: Use % 10 to get the last digit, and // 10 to remove it.
π Quick Reference
Basic While Loop Structure
variable = initial_value
while condition:
# Code to repeat
# ...
# Update the variable!
variable = new_valueCommon Loop Patterns
i = 1
while i <= n:
# do something
i += 1i = n
while i >= 1:
# do something
i -= 1total = 0
while condition:
total += valuex = ""
while x != "quit":
x = input("...")Checklist: Avoiding Infinite Loops
- β Is the loop variable initialized before the loop?
- β Is the loop variable updated inside the loop?
- β Will the update eventually make the condition false?
- β Is the update statement properly indented (inside the loop)?
β Key Takeaways
- β The
whileloop repeats code as long as a condition isTrue - β The condition is checked before each iteration
- β If the condition is
Falseinitially, the loop body never runs - β Always update the loop variable inside the loop to avoid infinite loops
- β Make sure the update is indented so it's inside the loop
- β Don't forget the colon (
:) after thewhilecondition - β
while True:creates an infinite loop (usually intentional) - β Use Ctrl+C to stop a runaway program
β Need Help?
If your program doesn't work, check these common issues:
- Program runs foreverβAre you updating the loop variable? Is the update indented correctly?
- Loop never runsβIs your initial value correct? Is your condition correct?
- Off by oneβCheck whether you need
<or<=(same for>) - SyntaxErrorβDid you forget the colon after
while? - IndentationErrorβIs all your loop code properly indented?
print() statements inside your loop to see what's happening:
count = 1
while count <= 5:
print("DEBUG: count =", count) # See the value each time
# ... rest of your code
count += 1