DEV Community

Emilio Ochieng
Emilio Ochieng

Posted on

Loops

Why loops matter

A loop is a control flow structure that executes a block of code repeatedly as long as a condition holds. They matter for three reasons: they reduce redundancy (no manually retyping the same statement), they save time and space (keeping code short and maintainable), and they handle dynamic data (processing a list or user input of any size without rewriting the code for each possible length).

for loops

Use a for loop when you know exactly what you're iterating over - a list, a range of numbers, the characters in a string:

items = ['sugar', 'salt', 'flour', 'soap', 'oil']
for i in items:
    print(i)

# output
# sugar
# salt
# flour
# soap
# oil
Enter fullscreen mode Exit fullscreen mode

for loops pair naturally with range() when you need to repeat something a fixed number of times rather than iterate over existing items:

for i in range(5):
    print("Attempt number", i)
Enter fullscreen mode Exit fullscreen mode

while loops

Use a while loop when the number of repetitions isn't known in advance and depends on a condition staying true:

count = 0
while count < 5:
    print(count)
    count += 1
Enter fullscreen mode Exit fullscreen mode

The loop keeps running as long as count < 5 evaluates to True. Forgetting to update count inside the loop is the classic mistake here - it creates an infinite loop, since the condition never becomes false.

break and continue

  • break exits the loop immediately, skipping any remaining iterations entirely.
  • continue skips just the current iteration and moves on to the next one, without exiting the loop.
for num in range(10):
    if num == 5:
        break          # stop the loop entirely once we hit 5
    print(num)
# prints 0, 1, 2, 3, 4

for num in range(10):
    if num % 2 == 0:
        continue        # skip even numbers, keep looping
    print(num)
# prints 1, 3, 5, 7, 9
Enter fullscreen mode Exit fullscreen mode

enumerate()

enumerate() gives you both the index and the value while looping over something - useful whenever you need to know where an item is, not just what it is:

items = ['sugar', 'salt', 'flour']
for index, item in enumerate(items):
    print(index, "->", item)

# output
# 0 -> sugar
# 1 -> salt
# 2 -> flour
Enter fullscreen mode Exit fullscreen mode

Without enumerate(), getting the index would mean manually tracking a separate counter variable and incrementing it yourself each pass through the loop.

Practical examples

Combining several of these — looping through a list, using enumerate() for numbering, and continue to skip an item that doesn't meet a condition:

prices = [180, 320, 85, 60, 0]

for index, price in enumerate(prices):
    if price == 0:
        continue   # skip invalid entries
    print(f"Item {index + 1}: KES {price}")
Enter fullscreen mode Exit fullscreen mode

What I understood from this

break and continue felt interchangeable at first glance, but they solve different problems - break is "I'm done here entirely," continue is "not this one, but keep going." Mixing them up either cuts a loop short when it should have kept processing the rest of the list, or keeps a loop running past a point where it should have stopped. enumerate() was the other thing that changed how I write loops day to day - before I understood it, I was manually creating and incrementing a counter variable alongside every for loop that needed one, which is exactly the kind of repetitive bookkeeping loops are supposed to eliminate in the first place.

Top comments (0)