Python while Loops
while Loops
Loops in Python
A loop executes a block of code repeatedly. Without loops, printing the numbers 1 to 100 would require 100 separate print() statements. With a loop, it takes two lines.
Python provides two primary looping constructs:
| Loop | Repeats | Best When |
|---|---|---|
while loop | As long as a condition remains true | You do not know in advance how many repetitions are needed |
for loop | Once for each item in a sequence (list, range, string, and so on) | You are processing a known collection of items |
This lesson focuses on the while loop.
The while Loop
A while loop runs a block of code as long as a condition evaluates to True.
Syntax
while condition:
# code to repeat
How It Works
- Python evaluates the condition.
- If it is
True, the indented block runs once. - Python goes back to step 1 and checks the condition again.
- When the condition becomes
False, the loop ends and the program continues after the loop.
Each pass through the loop body is called an iteration.
Example: Counting Numbers
count = 0
while count < 5:
print("Count value:", count)
count += 1
print("Loop ended")
Expected output:
Count value: 0
Count value: 1
Count value: 2
Count value: 3
Count value: 4
Loop ended
Tracing the loop:
| Iteration | count Before | count < 5 | Action |
|---|---|---|---|
| 1 | 0 | True | Print 0, increase to 1 |
| 2 | 1 | True | Print 1, increase to 2 |
| 3 | 2 | True | Print 2, increase to 3 |
| 4 | 3 | True | Print 3, increase to 4 |
| 5 | 4 | True | Print 4, increase to 5 |
| — | 5 | False | Loop ends |
- The loop runs while
count < 5. count += 1is essential. It movescounttoward the point where the condition becomesFalse.
Note: Always update the variable used in the condition inside the loop. Otherwise, the condition never changes and the loop never ends.
Infinite Loops
If the condition never becomes False, the loop runs forever — an infinite loop:
count = 0
while count < 5:
print("Count value:", count)
# count += 1 is missing — this loop never ends!
If this happens, stop the program by pressing Ctrl + C in the terminal.
Initializing the Loop Variable
The variable used in the condition must exist and have a value before the loop starts.
attempts = 1
while attempts <= 3:
print("Attempt number", attempts)
attempts += 1
Expected output:
Attempt number 1
Attempt number 2
Attempt number 3
Without the line attempts = 1, Python would raise a NameError the first time it evaluated attempts <= 3, because the variable would not exist yet.
The break Statement
break ends the loop immediately, even if the condition is still True. The program continues with the first statement after the loop.
Example: Stop When a Match Is Found
number = 1
while number <= 10:
if number == 6:
print("Number found, exiting loop")
break
print(number)
number += 1
Expected output:
1
2
3
4
5
Number found, exiting loop
- The loop stops as soon as
numberbecomes6. - The remaining iterations (6 to 10) never happen.
The continue Statement
continue skips the rest of the current iteration and jumps back to check the condition for the next iteration.
Example: Skip a Specific Value
value = 0
while value < 7:
value += 1
if value == 4:
continue
print("Current value:", value)
Expected output:
Current value: 1
Current value: 2
Current value: 3
Current value: 5
Current value: 6
Current value: 7
- When
valueis4,continueskips theprint(). - The loop then continues normally with
5.
Important: In this example,
value += 1comes beforecontinue. If the increment were placed after thecontinue, it would be skipped whenvalueis4,valuewould stay at4forever, and the loop would never end. Withwhileloops, always make sure the loop variable is updated before anycontinue.
The else Block in a while Loop
A while loop can have an optional else block. It runs once, when the loop condition becomes False naturally — that is, when the loop finishes without hitting break.
Example: Loop Completion Message
steps = 1
while steps <= 3:
print("Step", steps)
steps += 1
else:
print("All steps completed successfully")
Expected output:
Step 1
Step 2
Step 3
All steps completed successfully
- The
elseblock runs after the loop finishes normally. - It is useful for completion messages and for "not found" logic.
else Does Not Run After break
If the loop ends because of break, the else block is skipped.
x = 1
while x <= 5:
if x == 3:
break
print(x)
x += 1
else:
print("Loop finished")
Expected output:
1
2
"Loop finished" is not printed, because the loop exited early with break.
Practical Use of while–else: Searching
The else block is a clean way to report that a search found nothing:
numbers = [4, 9, 15, 22]
target = 10
index = 0
while index < len(numbers):
if numbers[index] == target:
print("Found at index", index)
break
index += 1
else:
print("Target not found")
Expected output:
Target not found
If the target is found, break runs and the else is skipped. If the loop checks every item without finding it, the else block reports the result.
The while True Pattern
When the stopping point is decided inside the loop, a common pattern is while True: combined with break:
attempts = 0
while True:
attempts += 1
print("Trying to connect... attempt", attempts)
if attempts == 3:
print("Connected!")
break
Expected output:
Trying to connect... attempt 1
Trying to connect... attempt 2
Trying to connect... attempt 3
Connected!
while True: would loop forever on its own; the break provides the exit. This pattern is widely used for input validation and retry logic.
Practical Example: Validating User Input
while True:
age_text = input("Enter your age: ")
if age_text.isdigit():
age = int(age_text)
break
print("Please enter a valid number.")
print("Your age is", age)
Example run:
Enter your age: twenty
Please enter a valid number.
Enter your age: 25
Your age is 25
The loop keeps asking until the input contains only digits. You cannot know in advance how many attempts the user will need, which is exactly the situation while loops are designed for.
Common Use Cases for while Loops
- Repeating a prompt until user input is valid
- Running background checks or polling for a status change
- Implementing retry mechanisms (for example, reconnecting to a server)
- Reading data until a condition is met
- Game loops that run until the player quits
Common Mistakes
| Mistake | Problem |
|---|---|
| Forgetting to update the loop variable | Infinite loop |
Updating the variable after continue | The update can be skipped, causing an infinite loop |
| Not initializing the loop variable | NameError |
Off-by-one conditions (< vs <=) | The loop runs one time too many or too few |
Using while to step through a list by index | Works, but a for loop is simpler and safer |
Related Concepts
- Python for Loops — iterating over sequences
- Python Range — generating number sequences for loops
- Python if Statement — conditions used inside loops
- Python pass Statement — placeholders in empty loop bodies