Table of Contents
Understanding `while` Loops in Python
A while loop repeats a block of code as long as a condition is True.
The general form is:
while condition:
# code to repeat
# (also called the loop body)- The
conditionis checked before every repetition. - If the condition is
True, the body runs. - When the condition becomes
False, the loop stops.
Basic `while` Loop Example
count = 1
while count <= 5:
print("Count is:", count)
count = count + 1
print("Loop finished!")What happens step-by-step:
- Start:
count = 1 - Check:
count <= 5→1 <= 5→True→ run the body - Print, then update:
countbecomes2 - Check again:
2 <= 5→ stillTrue→ run again
... - When
countbecomes6:6 <= 5→False→ loop ends
Key idea: Something inside the loop must change so that the condition eventually becomes False.
The Importance of Updating the Condition
If you forget to update the variable used in the condition, the loop may never stop.
Example: Infinite Loop (what *not* to do)
number = 1
while number <= 5:
print(number)
# Oops! We forgot: number = number + 1
Here, number is always 1, so number <= 5 is always True.
The loop runs forever (until you manually stop it).
Always check:
- Is my condition correct?
- Am I changing the variables used in the condition inside the loop?
`while` Loops and User Input
while loops are very useful when you don’t know in advance how many times you need to repeat something, especially with user input.
Repeating Until the User Types “quit”
command = ""
while command != "quit":
command = input("Enter a command (or 'quit' to stop): ")
print("You typed:", command)
print("Program ended.")- The loop keeps asking for input until the user types
"quit". - The condition
command != "quit"controls when the loop stops.
Validating User Input
You can use while to keep asking the user until they give a valid answer.
age = int(input("Enter your age (1-120): "))
while age < 1 or age > 120:
print("That doesn't look right.")
age = int(input("Please enter an age between 1 and 120: "))
print("Thanks! Your age is", age)The loop repeats only when the age is outside the allowed range.
Counting Up and Counting Down
while loops often use a counter variable that you increase or decrease each time.
Counting Up
i = 1
while i <= 3:
print("i is", i)
i = i + 1Output:
i is 1
i is 2
i is 3Counting Down
i = 3
while i > 0:
print("i is", i)
i = i - 1
print("Blast off!")Output:
i is 3
i is 2
i is 1
Blast off!Using `while` for Simple Games and Repeated Tasks
Because while loops can run an unknown number of times, they are perfect for:
- Simple guessing games
- Repeating a menu until the user chooses “exit”
- Repeating an action until a certain condition is met
Example: Guessing Until Correct
secret = 7
guess = int(input("Guess the number: "))
while guess != secret:
print("Wrong, try again!")
guess = int(input("Guess the number: "))
print("Correct! The secret number was", secret)
The loop only ends when guess == secret.
`while True` Loops
Sometimes you want a loop that runs “forever” until you manually break out of it from inside.
This is often written as:
while True:
# do something
# maybe break at some pointExample: menu that exits when the user chooses 4:
while True:
print("Menu:")
print("1. Say hello")
print("2. Say goodbye")
print("3. Do nothing")
print("4. Exit")
choice = input("Choose an option (1-4): ")
if choice == "1":
print("Hello!")
elif choice == "2":
print("Goodbye!")
elif choice == "3":
print("...")
elif choice == "4":
print("Exiting...")
break # leave the loop
else:
print("Invalid choice. Try again.")Here:
while True:means the loop condition is alwaysTrue.- The only way to leave the loop is with
break.
(The details of break and continue are covered in their own section; here you just see how break can stop a while loop.)
Common `while` Loop Patterns
1. Loop Until a Certain Count
count = 0
while count < 10:
print("Count is", count)
count = count + 12. Loop Until a Condition Becomes False
battery = 100
while battery > 0:
print("Battery at", battery, "%")
battery = battery - 10
print("Battery empty!")3. Loop Until a “Sentinel” Value
A sentinel is a special value that means “stop now”.
total = 0
print("Enter numbers to add. Enter 0 to finish.")
number = int(input("Number: "))
while number != 0:
total = total + number
number = int(input("Number: "))
print("Total is", total)
Here, 0 is the sentinel value that stops the loop.
Typical Mistakes with `while` Loops
1. Forgetting to Update the Variable
x = 0
while x < 5:
print(x)
# missing: x = x + 1 → infinite loop
Always ensure the loop body moves you toward the condition becoming False.
2. Using `==` Instead of `=`
=assigns a value.==compares values.
Inside the loop, you usually want = when you change a variable:
# Wrong:
x == x + 1 # This compares instead of updates
# Right:
x = x + 13. Condition That Is Never True or Never False
- If the condition is never
True, the loop body never runs. - If the condition is never
False, the loop never ends.
Examples:
# Never runs (x starts at 10, but you check for x < 5)
x = 10
while x < 5:
print(x)
x = x + 1
# Never stops (condition always true)
y = 1
while y > 0:
print(y)
y = y + 1When debugging, print the variables used in the condition to see how they change.
When to Use a `while` Loop
Use a while loop when:
- You don’t know in advance how many times you need to repeat something.
- You want to keep going until some condition changes (user input, a value reaches a limit, etc.).
- You’re reacting to something that happens over time (like a menu, a game loop, or repeated checks).
In later sections you will compare while loops to for loops and see when each is more convenient.