In Python, the while
loop allows you to repeatedly execute a block of code as long as a certain condition is true. The loop continues iterating as long as the condition remains true.
# Using a while loop to count from 1 to 5
count = 1
while count <= 5:
print(count)
count += 1
# Using a while loop with user input
password = "secret"
input_password = input("Enter the password: ")
while input_password != password:
print("Incorrect password. Try again.")
input_password = input("Enter the password: ")
print("Welcome! Access granted.")
# Using a while loop for indefinite repetition
running = True
while running:
user_input = input("Enter a command (quit to exit): ")
if user_input == "quit":
running = False
else:
print("Executing:", user_input)
It's important to ensure that the condition within the while
loop eventually becomes false; otherwise, the loop will run indefinitely (an infinite loop) and may crash your program.
You can use the break
statement to exit the loop prematurely when a certain condition is met.
# Using break to exit the loop
count = 1
while True:
print(count)
count += 1
if count > 5:
break
The while
loop is a powerful tool for performing repetitive tasks in Python, and you should use it judiciously to avoid infinite loops and ensure efficient code execution.