Python course menu
Python while Loops in Depth: Conditions, Sentinels and Input Loops
Go deeper with Python while loops: counting loops, loops that run until a goal is reached, sentinel values, input validation, guessing games, while True with break, and avoiding infinite loops.
On this page
A for loop repeats once per item. A while loop repeats as long as a condition is true, which makes it the right tool when you do not know in advance how many repetitions you need: until the user types "quit", until savings reach a goal, until a guess is correct.
The basic pattern#
count = 1
while count <= 5:
print(count)
count += 1
print("Done")1
2
3
4
5
DoneEvery working while loop has three parts:
- Set up a variable before the loop (
count = 1). - Test it in the condition, which is checked before every repetition.
- Change it inside the loop, so the condition eventually becomes false.
Looping until a goal is reached#
How many years until ₹1,000 doubles at 8% interest per year?
balance = 1000
year = 0
while balance < 2000:
balance *= 1.08
year += 1
print(year, round(balance, 2))10 2158.92You could not easily write this with for, because the number of years is the answer, not the input.
Counting digits#
n = 1234
digits = 0
while n > 0:
n //= 10
digits += 1
print(digits)4Each pass removes the last digit with floor division until nothing is left.
Sentinel values#
A sentinel is a special value that means "stop". Here, -1 ends the input:
total = 0
while True:
value = int(input("Number (-1 to stop): "))
if value == -1:
break
total += value
print("Total:", total)Number (-1 to stop): 5
Number (-1 to stop): 12
Number (-1 to stop): -1
Total: 17while True runs forever on its own; break is the only way out. This shape, "loop forever, break when done", is very common for reading input.
A guessing game#
secret = 6
guess = None
attempts = 0
while guess != secret:
guess = int(input("Guess (1-10): "))
attempts += 1
if guess < secret:
print("Too low")
elif guess > secret:
print("Too high")
print(f"Correct! {attempts} attempts.")Guess (1-10): 5
Too low
Guess (1-10): 8
Too high
Guess (1-10): 6
Correct! 3 attempts.guess starts as None so the condition is true on the first check. For a real game, pick the secret with random.randint(1, 10) (see Modules).
Looping while a collection has items#
Because non-empty lists are truthy, while items: keeps going until the list is empty:
stack = [1, 2, 3]
while stack:
print("popped", stack.pop())popped 3
popped 2
popped 1Infinite loops#
If nothing inside the loop ever makes the condition false, it never ends. This loop forgets to update count:
count = 1
while count <= 5:
print(count)
# missing: count += 1It prints 1 forever. Press Ctrl + C in the terminal to stop it. When a loop seems stuck, check that the variable in the condition really changes.
for or while?#
Common mistakes#
Practice#
Practice exercise
The Collatz sequence starts at a number n. If n is even, halve it; if odd, replace it with 3n + 1. Repeat until n is 1. Starting from n = 6, print the full sequence and the number of steps.
Show hint
Loop while n != 1, append each new value to a list, and count the steps.
Show solution
n = 6
steps = 0
sequence = [n]
while n != 1:
n = n // 2 if n % 2 == 0 else 3 * n + 1
steps += 1
sequence.append(n)
print(sequence, steps)[6, 3, 10, 5, 16, 8, 4, 2, 1] 8Nobody knows how many steps a given starting number needs until you run it (27 takes 111 steps), which is exactly why this is a job for while.
Key takeaway#
Finished this lesson?