Python While Loops
In Python, a while loop repeatedly executes a block of code as long as a specified condition evaluates to True. It’s useful when you don’t know the exact number of iterations in advance and want to keep executing as long as a condition holds.
Basic Syntax of a while loop:
while condition:
# Code block to be executed as long as the condition is True
1. Simple Example
Here’s an example where the loop runs as long as the variable x is less than 5:
x = 0
while x < 5:
print(x)
x += 1 # Increment x by 1 each time
Output:
0
1
2
3
4
In this example, the while loop continues as long as x < 5. Each time the loop runs, the value of x is printed, and then x is incremented by 1.
2. Infinite Loop
A while loop can create an infinite loop if the condition never becomes False. Be cautious with this, as it may cause your program to run forever.
Example:
while True:
print("This loop will run forever.")
This loop will keep printing indefinitely because the condition True is always satisfied. To stop it, you would need to manually interrupt the execution (e.g., using Ctrl + C in the terminal).
3. Breaking out of a While Loop
You can use the break statement to exit the loop early, even if the condition is still True. This is useful when you want to stop looping based on some other condition.
Example:
x = 0
while x < 5:
if x == 3:
break # Exit the loop when x is 3
print(x)
x += 1
Output:
0
1
2
In this example, the loop stops when x reaches 3 because of the break statement.
4. Skipping an Iteration (continue)
The continue statement allows you to skip the rest of the code inside the loop for the current iteration and move to the next iteration.
Example:
x = 0
while x < 5:
x += 1
if x == 3:
continue # Skip the print when x is 3
print(x)
Output:
1
2
4
5
In this case, when x == 3, the continue statement skips the print(x) line and moves to the next iteration.
5. Using While Loops with Conditions
You can use more complex conditions in while loops, including logical operators.
Example:
x = 0
while x < 10:
if x % 2 == 0: # Check if x is even
print(f"{x} is even")
else:
print(f"{x} is odd")
x += 1
Output:
0 is even
1 is odd
2 is even
3 is odd
4 is even
5 is odd
6 is even
7 is odd
8 is even
9 is odd
In this example, the while loop runs until x reaches 10, and the program prints whether x is even or odd.
6. Else Clause with While Loop
Python allows an else clause with a while loop. The else block is executed when the while loop terminates normally, meaning when the condition becomes False. If the loop is exited via break, the else block will not be executed.
Example:
x = 0
while x < 5:
print(x)
x += 1
else:
print("Loop finished successfully!")
Output:
0
1
2
3
4
Loop finished successfully!
Example with break:
x = 0
while x < 5:
print(x)
if x == 3:
break
x += 1
else:
print("Loop finished successfully!") # This won't be printed because the loop was broken
Output:
0
1
2
3
In this case, the else block does not execute because the loop was exited early due to the break.
7. Using While Loops with Collections
You can also use a while loop to iterate over a collection such as a list by checking the condition using an index.
Example:
fruits = ["apple", "banana", "cherry"]
index = 0
while index < len(fruits):
print(fruits[index])
index += 1
Output:
apple
banana
cherry
Summary of while Loops:
whileloop: Executes a block of code as long as a condition isTrue.break: Stops the loop execution immediately.continue: Skips the current iteration and proceeds with the next one.else: Executes if the loop ends normally (not viabreak).- Infinite loop: Can be created by using a condition like
while True, but must be stopped manually (withbreakor other mechanisms).