While Loop Syntax
The basic structure of a Python while loop is:
while condition:
# Code to execute while condition is True
# IMPORTANT: Something here must eventually make condition False
The loop checks the condition before each iteration. If the condition is False from the start, the loop body never runs. If the condition never becomes False, the loop runs forever (an infinite loop).
Basic While Loop Examples
Counting with While
# Count from 1 to 5
count = 1
while count <= 5:
print(f"Count: {count}")
count += 1 # Without this, the loop would run forever!
print("Done!")
Every element has a role:
count = 1β Initialize the counter before the loopwhile count <= 5β Check the conditioncount += 1β Update the counter to avoid an infinite loop
Countdown Timer
countdown = 10
while countdown > 0:
print(f"T-minus {countdown}...")
countdown -= 1
print("π Liftoff!")
While Loop for User Input Validation
One of the most common real-world uses of while is validating user input β keep asking until you get a valid answer:
# Keep asking until a valid age is entered
age = -1 # Initialize with an invalid value
while age < 0 or age > 120:
age_input = input("Enter your age (0-120): ")
if age_input.isdigit():
age = int(age_input)
if age < 0 or age > 120:
print("Age must be between 0 and 120.")
else:
print("Please enter a valid number.")
print(f"Your age is: {age}")
While-Else Clause
Python's while loop has an optional else clause that runs when the condition becomes False (but NOT when the loop is exited with break):
# Search for a number with while-else
target = 7
num = 1
while num <= 10:
if num == target:
print(f"Found {target}!")
break
num += 1
else:
# Only runs if loop completed WITHOUT break
print(f"{target} not found in range 1-10")
# Another example: login attempts
attempts = 0
max_attempts = 3
password = "secret123"
while attempts < max_attempts:
guess = input("Enter password: ")
attempts += 1
if guess == password:
print("Access granted!")
break
else:
print("Too many failed attempts. Account locked.")
Infinite Loops with Break
Sometimes you intentionally create an infinite loop (while True) and exit it with break when a condition is met. This is common in menus, game loops, and server applications:
# A simple command-line menu
while True:
print("\n--- Menu ---")
print("1. Say Hello")
print("2. Add Numbers")
print("3. Exit")
choice = input("Enter choice (1-3): ")
if choice == "1":
name = input("Your name: ")
print(f"Hello, {name}!")
elif choice == "2":
a = float(input("First number: "))
b = float(input("Second number: "))
print(f"Sum: {a + b}")
elif choice == "3":
print("Goodbye!")
break
else:
print("Invalid choice. Try again.")
Nested While Loops
# Multiplication table using nested while
row = 1
while row <= 5:
col = 1
while col <= 5:
print(f"{row * col:3}", end="")
col += 1
print() # New line after each row
row += 1
For Loop vs While Loop
| Feature | For Loop | While Loop |
|---|---|---|
| When to use | Known number of iterations or iterating a sequence | Unknown iterations, condition-based |
| Typical use | Iterating lists, ranges, strings | User input, game loops, polling |
| Infinite loop risk | Very low | Higher (easy to forget update) |
| Counter management | Automatic | Manual |
| Readability | More readable for sequences | More readable for conditions |
Common Mistakes
Mistake 1: Forgetting to Update the Condition Variable
# β INFINITE LOOP - never terminates!
x = 0
while x < 5:
print(x)
# Missing: x += 1
# β
Correct
x = 0
while x < 5:
print(x)
x += 1
If your program gets stuck in an infinite loop, press Ctrl+C in the terminal to send a KeyboardInterrupt and stop execution.
Mistake 2: Off-by-One Errors
# Want to print 1 through 10
i = 1
while i < 10: # β Stops at 9, not 10
print(i)
i += 1
i = 1
while i <= 10: # β
Correctly goes to 10
print(i)
i += 1
ποΈ Practical Exercise
- Write a while loop that prints all even numbers from 2 to 20.
- Write a program that sums numbers entered by a user until they enter 0.
- Create a simple guessing game: pick a number 1-10, let the user guess until correct, tell them if their guess is too high or too low.
π₯ Challenge Exercise
Build a text-based ATM simulator using while loops. The account starts with $1000. The menu should have: Check Balance, Deposit, Withdraw, and Exit. Validate that withdrawals don't exceed the balance. Count and display total transactions when exiting.
Interview Questions
- What is the difference between a for loop and a while loop in Python?
- What happens if a while loop condition never becomes False?
- What does the else clause in a while loop do?
- When would you use while True with break instead of a regular condition?
- How do you avoid infinite loops when writing while loops?
- What is the difference between break and continue in a while loop?
π Summary
- A
whileloop repeats code as long as its condition isTrue. - Always ensure something inside the loop will eventually make the condition
False. - The optional
elseclause runs when the condition becomes False (not when broken out withbreak). while Truecreates an intentional infinite loop β usebreakto exit.- Use
whilewhen you don't know in advance how many iterations are needed. - Press Ctrl+C to interrupt an accidentally infinite loop.
Related Topics
FAQ
Yes, using an index counter: i = 0; while i < len(my_list): ... i += 1. But a for loop is much more readable for this purpose. Use for loops to iterate collections, and while loops for condition-based repetition.
Python doesn't have a do-while loop. The closest equivalent is while True: ... if condition: break. This guarantees the loop body runs at least once before checking the exit condition.
Use time.sleep(seconds) from the time module: import time; time.sleep(1) pauses for 1 second. This is commonly used in polling loops that check for new data at intervals.