While Loops
A while loop runs a block of code as long as a condition is true. Instead of looping over a sequence, you keep repeating until something changes and the condition becomes false.
Basic syntax
while condition:
# code to run while condition is trueThe condition is checked before each iteration. When it becomes False, the loop stops and the program continues after it.
Basic example
count = 1
while count <= 5:
print(count)
count += 1
# Output: 1 2 3 4 5What happens each time through the loop:
- Check: is
count <= 5? - If yes, run the indented block (print, then add 1)
- When
countreaches 6, the condition is false, so the loop ends
If nothing inside the loop changes the condition, it will never become False and your program will run forever. Make sure something inside the loop moves toward ending it.
Infinite loops
A loop that never stops is called an infinite loop. This usually happens by accident:
# Infinite loop — count never changes!
count = 1
while count <= 5:
print(count)If your program freezes, an infinite loop is often why. Press Ctrl + C in the terminal to stop it.
Sometimes infinite loops are intentional — a game loop or a program waiting for input — but you should always have a way to break out of them.
Validating user input
while loops are great for repeating a prompt until the user gives a valid answer:
age = int(input("Enter your age: "))
while age < 0:
print("Age can't be negative.")
age = int(input("Enter your age: "))
print(f"Your age is {age}.")The loop keeps asking until age is 0 or greater.
Stopping on a specific input
You can also let the user exit the loop by typing a specific value. Use break to stop the loop immediately:
while True:
answer = input("Enter a number (or 'q' to quit): ")
if answer == "q":
break
print("You entered:", answer)
print("Goodbye!")while True creates an intentional infinite loop — it only ends when break is hit. This pattern is common when you want to keep a program running until the user decides to stop.
break exits the loop immediately, skipping the rest of the current iteration and the condition check. The program continues with whatever comes after the loop.
When to use a while loop
Use a while loop when you don’t know in advance how many iterations you need — you just know the condition that should keep things going. If you’re stepping through a list or a fixed range, a for loop is usually cleaner.
| Situation | Loop to use |
|---|---|
| Loop a fixed number of times | for with range() |
| Loop over every item in a list | for |
| Loop until a condition changes | while |
| Keep asking until valid input | while |
Summary
- A
whileloop repeats as long as its condition stays true. - Make sure something inside the loop changes so the condition can eventually become false.
- Use
whilewhen you don’t know how many times you’ll need to repeat.