Python - While Loop

01-Feb-2024

Dive into the world of while loops in Python. Learn how to create loops based on conditional expressions, enabling iterative processes until specified conditions are met.

Introduction

Python's while loop is a flexible pattern that repeatedly runs a piece of code if a given condition is met. This page offers explanations of the while loop's usage in addition to real-world examples that demonstrate how to use it.



Example :


# Example: Simple While loop
count = 0
while count < 5:
# Loop body
print(count) count += 1


Infinite Loop

When using `while` loops, exercise caution to prevent accidental endless loops. Make sure the loop contains a way to finally set the condition to False, or use break to break out of the loop.


Example :



# Example: Infinite While loop

while True: # Loop body print("This is an infinite loop!")


Else Clause

The `while` loop, like the `for` loop, can also have a `else` clause that gets performed when the loop condition turns False. In the event that a break statement ends the loop, it is not executed.


Example :


# Example: While loop with else
counter = 0
while counter < 5:
# Loop body
print("Iteration : ", counter)
counter += 1
else: # Executed when the condition becomes False
print("Loop completed!")


Notes
- When the number of iterations is unknown in advance, the `while` loop works well.
- To prevent infinite loops, make sure there's a way to eventually set the loop condition to False.
- Code can be executed using the `else` clause in the event that the loop condition turns False.


Conclusion
In Python, handling repetitive tasks requires an understanding of and proficiency with the `while` loop. The `while` loop provides an effective option for situations requiring the iteration of dynamic data or the implementation of specified conditions.


Comments