Computers are brilliant at repetition — they never get bored, never lose count, and never make careless mistakes. Loops let you tell a program to do something over and over without writing the same code hundreds of times. The while loop is one of two major loop types in Python, and it keeps going for as long as a condition is True.
How a While Loop Works
while condition:
# indented block runs repeatedly
Before each repetition (called an iteration), Python checks the condition. If it is True, the block runs. If it is False, the loop ends and the program continues past it.
count = 1
while count <= 5:
print(count)
count += 1
print("Done!")
Output:
1
2
3
4
5
Done!
The line count += 1 is crucial. It updates the variable that the condition checks. Without it, count would stay at 1 forever and the loop would never stop — this is called an infinite loop.
Infinite Loops
An infinite loop runs forever because its condition never becomes False. This will hang your program:
count = 1
while count <= 5:
print(count)
# forgot count += 1 — loops forever!
Always make sure your while loop has a way of eventually becoming False. The most common fix is to change the variable the condition depends on inside the loop body.
If your program seems frozen, you may have accidentally created an infinite loop. In most environments you can stop it by pressing Ctrl+C.
While Loops with User Input
While loops are especially useful when you want to keep asking a user for input until they give a valid answer:
password = ""
while password != "secret123":
password = input("Enter the password: ")
print("Access granted!")
You cannot use a for loop here because you do not know in advance how many attempts the user will need.
The break Statement
Sometimes you want to exit a loop early based on a condition inside the body. The break statement jumps out of the loop immediately:
attempts = 0
while True: # loop runs until a break
guess = int(input("Guess the number (1-10): "))
attempts += 1
if guess == 7:
print(f"Correct! You took {attempts} attempts.")
break
print("Try again!")
while True deliberately creates an infinite loop, and break provides the only way out. This is a recognised and clean pattern.
Use a while loop when you cannot predict how many iterations are needed — for example, reading user input until it is valid, or processing data until a certain event occurs. If you know the number of repetitions in advance, a for loop is usually cleaner.
A Practical Example
balance = 100
while balance > 0:
spend = int(input("How much would you like to spend? "))
if spend > balance:
print(f"Not enough funds. Balance: £{balance}")
else:
balance -= spend
print(f"Remaining balance: £{balance}")
print("Account empty.")
Practice Problems
What is wrong with this code? x = 10; while x > 0: print(x)
Show answer
Give one situation where a while loop is more appropriate than a for loop.