Skip to content
Foxipa

Suggest an edit

Tell us what should be corrected, clarified, or improved. Submission will be connected to Foxipa’s contribution service later.

No information is sent anywhere yet. Your suggestion is only prepared in your browser.

Learning

Python Loops

Learn repetition the Python way: for loops over sequences and range, while loops over conditions, break and continue, and enumerate for the times position matters.

Levels: Beginner ~15 min read

Basic

Computers earn their keep by repeating without complaint, and Python has exactly two loops: for, which walks a sequence it can see, and while, which repeats as long as a condition holds. Between them, plus break and continue for the exits, they cover every kind of repetition there is. The craft is choosing the loop that makes the stopping condition obvious, because the stopping condition is where loops go wrong.

for: walking what you can see

A Python for loop is a for-each. It takes each element of a sequence, a list, a string, a dictionary's keys, the lines of a file, and runs the block with that element bound to a name. There is no counter to increment and no off-by-one unless you invite one.

python foreach.py
1
2
3
4
5
for bread in ["sourdough", "rye", "flatbread"]:
    print(f"Baking {bread}")

for letter in "rye":
    print(letter)   # r, y, e, one per line

One loop, every sequence.

When the thing to walk is a count rather than a collection, range() manufactures the numbers on demand: range(5) counts 0 through 4, range(2, 6) counts 2 through 5, and range(0, 12, 3) counts by threes. Like slicing, the stop value is excluded, and the arithmetic stays consistent with everything else in the language.

while: repeating until something changes

A while loop tests a condition before each pass and runs the block while it holds. It is the honest choice when you cannot know the number of repetitions in advance, feeding people until the bread runs out, retrying until an answer arrives, converging until a value settles. Its responsibility is yours: something inside the block must move the world toward the condition becoming false, or the loop simply never stops.

python while.py
1
2
3
4
5
6
7
8
9
loaves = 3
customers = 0

while loaves > 0:
    customers += 1
    loaves -= 1
    print(f"Served customer {customers}; {loaves} left")

print(f"Sold out after {customers} customers")

Repetition whose length nobody could predict, which is exactly while's job.

break and continue: the exits

break leaves the loop entirely from the inside, the tool for stop when you find it, and continue skips the rest of this pass and takes the next one, the tool for skip this one, move along. Both are clearer than the alternatives they replace, flag variables and deeply nested ifs, and both read best near the top of a loop, guarding the pass, rather than buried in its middle.

python exits.py
1
2
3
4
5
6
7
8
orders = ["rye", "PAID", "sourdough", "CANCELLED", "flatbread"]

for order in orders:
    if order == "CANCELLED":
        break        # stop the whole run
    if order == "PAID":
        continue     # skip this pass
    print(f"To bake: {order}")

One loop, two different ways out early.

enumerate: when position matters

The moment you write for i in range(len(items)): you are working against the grain. When the position genuinely matters, enumerate(items) yields pairs of index and element, optionally starting anywhere with start. The loop reads as what it is, walking items that happen to be numbered, rather than walking numbers that happen to index items.

Bake the morning batch

The example below runs one morning at the bakery with all three loop shapes: a for over the batch list, an enumerate for the numbered queue, and a while that serves until the bread runs out. Run it, then push on the exits: add "CANCELLED" to the batch and stop the whole run with break, or add an item the bakery does not sell and skip it with continue. Then make the while-loop classic on purpose: delete the loaves -= 1 line and watch the morning never end.

Interactive Runnable example
Edit

Ready to run.

What to notice

  • The three loop shapes each had a natural job: walking a known list, numbering a queue, repeating until a condition changed.

  • The while condition carried two facts, loaves > 0 and served < len(queue), so it stopped when either the bread or the queue ran out.

  • Slicing was never needed to number the queue; enumerate supplied positions without a counter to manage.


Quick check

If you can pick between for and while by looking at what decides the stopping, use break and continue where they read best, and number a loop with enumerate instead of range(len(...)), repetition costs you nothing. The last stop on the path: functions, where the useful parts of these loops get names. When you are ready, take the Python Loops quiz.

Was this page helpful?

Mark this learning resource complete to track your learning progress.