Python While Loops
A while loop in Python repeatedly executes a block of code as long as the specified condition is true.
1. Basic While Loop
The basic syntax of a while loop is:
while condition:
# code block
The code block inside the loop will continue to execute as long as the condition remains true.
Example:
i = 1
while i <= 5:
print(i)
i += 1
2. Infinite While Loop
If the condition in a while loop always evaluates to true, it will result in an infinite loop.
Example:
while True:
print("This is an infinite loop")
3. Using Break Statement
The break
statement can be used to exit the loop prematurely based on a certain condition.
Example:
i = 1
while True:
print(i)
if i == 5:
break
i += 1
4. Using Continue Statement
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.
Example:
i = 0
while i < 5:
i += 1
if i == 3:
continue
print(i)
Conclusion
While loops are useful when you need to execute a block of code repeatedly based on a condition. However, you should be careful to avoid infinite loops and ensure that the loop eventually terminates.