Python While Loops
While Loop Basics
A while loop executes a block of code repeatedly as long as its condition evaluates to True. It’s useful when the number of iterations isn’t predetermined.
Example
# Basic while loop
count = 1
while count <= 5:
print(f"Count: {count}")
count += 1
print("Loop finished!")
Output
Count: 1 Count: 2 Count: 3 Count: 4 Count: 5 Loop finished!
While Loop with Break and Continue
Control loop execution with `break` to exit early, or `continue` to skip to the next iteration.
Example
# While loop with break and continue
num = 0
while num < 10:
num += 1
if num % 2 == 0:
continue # Skip even numbers
if num == 7:
break # Exit loop when num is 7
print(f"Current number: {num}")
print("Loop ended")
Output
Current number: 1 Current number: 3 Current number: 5 Loop ended
While-Else Statement
A while loop can include an `else` clause. The `else` block runs only if the loop finishes normally (not interrupted by `break`).
Example
# While-else example
count = 1
while count <= 3:
print(f"Count: {count}")
count += 1
else:
print("Loop completed normally")
# With break
count = 1
while count <= 3:
if count == 2:
break
print(f"Count: {count}")
count += 1
else:
print("This won't execute due to break")
Output
Count: 1 Count: 2 Count: 3 Loop completed normally Count: 1
Infinite Loops and User Input
Use a `while True` loop for programs that should run indefinitely until explicitly broken, such as interactive menus.
Example
# Interactive menu with while loop
while True:
print("\nMenu:")
print("1. Option 1")
print("2. Option 2")
print("3. Quit")
choice = input("Enter your choice: ")
if choice == "1":
print("You selected Option 1")
elif choice == "2":
print("You selected Option 2")
elif choice == "3":
print("Goodbye!")
break
else:
print("Invalid choice. Please try again.")
Output
Menu: 1. Option 1 2. Option 2 3. Quit Enter your choice: 1 You selected Option 1 Menu: 1. Option 1 2. Option 2 3. Quit Enter your choice: 3 Goodbye!