In Python, a while loop is used to repeatedly execute a block of code as long as a specified condition is true. Here's how you can use while loops:
x = 0
while x < 5:
print(x)
x += 1
This loop will print numbers from 0 to 4. It will keep iterating as long as x is less than 5.
You can include an else block that will execute when the condition of the while loop becomes false.
x = 0
while x < 5:
print(x)
x += 1
else:
print("Loop ended because x is no longer less than 5")
Be cautious with while loops to avoid creating infinite loops (loops that never end). You can use a break statement to exit the loop when a certain condition is met.
x = 0
while True:
print(x)
x += 1
if x == 5:
break
You can also nest while loops within each other.
x = 0
y = 0
while x < 3:
while y < 3:
print(f"x: {x}, y: {y}")
y += 1
x += 1
y = 0
The continue statement can be used to skip the rest of the code inside the loop for the current iteration and proceed to the next iteration.
x = 0
while x < 5:
x += 1
if x == 3:
continue
print(x)
while loops are often used for accepting user input until a certain condition is met.
while True:
user_input = input("Enter a number (or 'q' to quit): ")
if user_input.lower() == 'q':
break
print(f"You entered: {user_input}")
Similar to if statements, you can include an else block with a while loop. The else block executes when the condition becomes false.
x = 0
while x < 5:
print(x)
x += 1
else:
print("Loop ended because x is no longer less than 5")
These are some common patterns for using while loops in Python. They are useful for situations where you need to repeat a block of code until a condition is no longer true.