Python while Loop
In Python, the while
loop is used to repeatedly execute a block of code as long as a specified condition is true. The basic syntax of a while
loop is as follows:
while condition:
# Code to be executed while the condition is True
Here's a more detailed breakdown:
- The
while
keyword is used to start the loop. condition
is an expression that is evaluated before each iteration. If the condition isTrue
, the code block inside the loop is executed. If the condition isFalse
, the loop is exited.- The indented code block following the
while
statement is the body of the loop, and it is executed repeatedly as long as the condition isTrue
.
Example:
count = 0
while count < 5:
print(count)
count += 1
In this example, the while
loop prints the value of count
and increments it by 1 in each iteration until count
becomes equal to or greater than 5.
Using break
and continue
:
count = 0
while count < 10:
print(count)
count += 1
if count == 5:
break # Exit the loop when count is 5
while count < 15:
count += 1
if count == 12:
continue # Skip the rest of the code and move to the next iteration when count is 12
print(count)
The break
statement is used to exit the loop prematurely when a certain condition is met, and the continue
statement is used to skip the rest of the code in the loop for the current iteration and move to the next iteration.
Infinite Loop:
A common pattern with while
loops is to create an infinite loop that continues until a specific condition is met or until the loop is explicitly terminated using a break
statement.
while True:
user_input = input("Enter 'quit' to exit: ")
if user_input.lower() == 'quit':
break
else:
print(f"You entered: {user_input}")
In this example, the loop continues indefinitely until the user enters 'quit', at which point the loop is exited using the break
statement.
The while
loop is useful when you want to repeat a block of code as long as a certain condition is true. It provides flexibility for scenarios where the number of iterations is not known beforehand. However, be cautious to avoid creating infinite loops unintentionally.