DEV Community

Cover image for While Loops: Repetition with Control in Python
Mary Nyandia
Mary Nyandia

Posted on

While Loops: Repetition with Control in Python

Basic While Loop
While loops run as long as a condition is true. This makes them flexible for tasks where the number of repetitions isn’t known in advance.

count = 1
while count <= 5:
    print("Count is", count)
    count += 1

Enter fullscreen mode Exit fullscreen mode

Break Statement
break lets you exit a loop early, even if the condition is still true. This is useful for stopping once a certain condition is met.

number = 0
while True:
    number += 1
    if number == 3:
        break

Enter fullscreen mode Exit fullscreen mode

Continue Statement
continue skips the rest of the loop for the current iteration and moves to the next one. This is handy for filtering data during iteration.

n = 0
while n < 5:
    n += 1
    if n % 2 == 0:
        continue
    print("Odd number:", n)

Enter fullscreen mode Exit fullscreen mode

My Take
While loops provide flexibility by running until conditions change. Combined with break and continue, they give fine‑grained control over repetition.

Top comments (0)