DEV Community

Fidel Okumu
Fidel Okumu

Posted on

Loops: Repeating Work Without Repeating Code

Introduction
A huge part of programming is doing the same action many times — checking every driver in a list, processing every row of data, or repeating a task until a condition is met. Loops are how Python handles this without forcing me to copypaste the same line over and over.
For Loops
A for loop runs a block of code once for every item in a collection.

What I understood here: driver is a temporary variable that takes on each value in drivers, one at a time in order. The loop runs exactly as many times as there are items in the list four times, in this case.

While Loops
A while loop repeats until a condition becomes false, rather than looping over a fixed collection.

The detail that took the most getting used to: the condition is checked before every round, and the loop starts counting from 0. So while rides_completed < 3 actually runs 3 times (for 0, 1, 2), not what I initially assumed. Forgetting the += 1 line entirely would make the condition stay true forever, causing an infinite loop — one of the most common mistakes with while loops.

Break and Continue
These give more control over a loop's execution:

The distinction: break exits the loop immediately and nothing after it runs, not even for remaining items. continue only skips the current round the loop still checks every other item normally.

Enumerate()
Sometimes I need both the item and its position in the list. Enumerate() provides both at once:

What I Learned
I learned that loops allow Python to repeat instructions automatically until a certain condition is met or until all items have been processed.

Top comments (0)