The while loop in Python is used to execute a block of code repeatedly as long as a specified condition is True. It is useful for situations where the number of iterations is not known beforehand and depends on a condition.
Example
counter = 1
while counter <= 5:
print(f"Counter: {counter}")
counter += 1
Output:
Counter: 1
Counter: 2
Counter: 3
Counter: 4
Counter: 5
Syntax
while condition:
# Code to execute repeatedly
- condition: A Boolean expression that determines whether the loop should continue. If True, the loop executes; if False, the loop terminates.
Why Use while?
- Indeterminate Iterations: Use while when the number of iterations is not fixed and depends on a condition.
- Event-Driven Loops: For tasks like waiting for user input, monitoring states, or reading files until EOF.
- Flexible Logic: Can be used with complex conditions for dynamic looping.
Common Examples
1. Basic While Loop
x = 0
while x < 5:
print(x)
x += 1
Output:
0
1
2
3
4
2. Using a Break Statement
x = 1
while True:
print(x)
if x == 5:
break # Exit the loop when x reaches 5
x += 1
Output:
1
2
3
4
5
3. Using a Continue Statement
x = 0
while x < 5:
x += 1
if x == 3:
continue # Skip the rest of the loop for x == 3
print(x)
Output:
1
2
4
5
4. Validating User Input
while True:
name = input("Enter your name: ")
if name.strip():
print(f"Hello, {name}!")
break # Exit loop if input is valid
Input/Output:
Enter your name:
Enter your name: John
Hello, John!
5. Calculating a Sum
numbers = [1, 2, 3, 4, 5]
total = 0
i = 0
while i < len(numbers):
total += numbers[i]
i += 1
print(f"Sum: {total}")
Output:
Sum: 15