capypad
0 day streak
python / beginner
Snippet

Using a While Loop for Repeated Tasks

A while loop repeats a block of code as long as a specific condition remains true. It is useful when you don't know the exact number of iterations in advance.

snippet.py
python
1
2
3
4
counter = 1
while counter <= 3:
print("Loop number:", counter)
counter += 1
Breakdown
1
while counter <= 3:
Checks if the counter is less than or equal to 3 before each loop.
2
counter += 1
Increments the counter by 1 to eventually make the condition false.