g↗genai/ learner
Python for AI / Lesson 08

Loops

A loop repeats one block of code once for each item in a list, or for as long as a condition is True, so you write the steps once instead of over and over.

Concept + interactive labBeginner friendly

Loops: Repeating the same steps for each item.

Think of a post office worker who takes each parcel off a conveyor belt, reads its label, and does the same job for it. A Python loop works the same way. You will meet these terms in order:

  1. Loop variable and body: in for p in parcels:, p is the loop variable. It holds one item per pass. The indented lines under the colon are the body, which runs once per pass.
  2. Accumulator: a variable you set before the loop and update inside it, such as a running count.
  3. break: stops the whole loop at once.
  4. continue: skips the rest of the current pass and moves on to the next item.
  5. while loop and condition: a loop that repeats while a condition is True. In this lesson a condition is a test such as i < 5, which gives True or False.
  6. Infinite loop: a loop whose condition never becomes False and whose body never runs break, so it never stops on its own.
Running example (toy data)

Each parcel's status is stored as text in a list. These five values are invented for this lesson:

parcels = ["sent", "lost", "sent", "returned", "sent"]

A for loop visits each item in order.

for p in parcels: starts the loop. Python takes the first item, stores it in p, and runs the body. Then it takes the next item, and so on, until the list has no items left.

parcels = ["sent", "lost", "sent", "returned", "sent"]
for p in parcels:
    print(p)

# Output:
# sent
# lost
# sent
# returned
# sent
Row of five parcel cards labelled sent, lost, sent, returned, and sent, with an amber frame that moves one card at a time from left to right to show a for loop visiting each item once, in order.
One pass per item: the loop variable holds one card at a time, from the first to the last.

The loop variable holds the item itself, not its position. On the first pass p is "sent", not 0. To get positions as numbers you would need range(len(parcels)), which this lesson does not cover.

Everyday analogy: a teacher reads each name on the class register once, in order. If the register is empty, the teacher reads nothing. In the same way, a loop over an empty list never runs its body.

Accumulators: Building a count while you loop.

An accumulator collects a result across passes. This loop counts how many parcels say "sent":

parcels = ["sent", "lost", "sent", "returned", "sent"]
count = 0                      # set before the loop
for p in parcels:
    if p == "sent":
        count += 1             # update inside the loop
print(count)                   # 3

count += 1 is shorthand for count = count + 1. The update runs only on passes where the if condition is True. Pass by pass:

  • Pass 1, "sent": count becomes 1.
  • Pass 2, "lost": count stays 1.
  • Pass 3, "sent": count becomes 2.
  • Pass 4, "returned": count stays 2.
  • Pass 5, "sent": count becomes 3.

Everyday analogy: a clicker counter at a door. You press it only for people who match what you are counting, and the number keeps the total between presses.

break stops the loop; continue skips one pass.

break leaves the loop at once. Code after the loop still runs, but the remaining items are never visited.

parcels = ["sent", "lost", "sent", "returned", "sent"]
for p in parcels:
    if p == "lost":
        break                  # leave the loop now
    print(p)
print("done")                  # runs after the loop

# Output:
# sent
# done
The same five parcel cards: the first card passes to a printed tray, the second card, lost, is stopped by a red sign labelled break, and the last three cards are faded and marked not visited, showing that the loop ends at the lost card.
break ends the loop at the item that triggers it. The cards after it are never reached.

continue is different. It skips only the rest of the current pass, then the loop moves on to the next item:

parcels = ["sent", "lost", "sent", "returned", "sent"]
for p in parcels:
    if p == "returned":
        continue               # skip this pass only
    print(p)

# Output:
# sent
# lost
# sent
# sent

Common mistake: continue does not end the loop. The "returned" parcel is skipped, but the last "sent" still prints.

Everyday analogy: break is the post office closing its counter early. continue is skipping one parcel on the belt and serving the next.

A while loop repeats while a condition is True.

A while loop checks its condition before every pass. If the condition is True, the body runs. If it is False, the loop ends. Unlike for, a while loop does not pick up the next item for you. To walk a list with while, you manage a counter yourself. Use it when the number of passes depends on a condition, such as retrying until something succeeds. For a plain list, a for loop is simpler.

parcels = ["sent", "lost", "sent", "returned", "sent"]
i = 0                                # the counter
while i < len(parcels):              # condition, checked each pass
    print(parcels[i])                # read the item at position i
    i += 1                           # move the counter forward

# Output: the same five lines as the for loop
Flow diagram of a while loop drawn left to right: a start box feeds a box labelled Set counter, then a Check condition diamond. True leads to Run body, which contains Update counter; an arrow returns from Update counter to Check condition. False leads to Exit loop.
The counter is set once before the loop. The return arrow goes back to the condition check, so the condition is tested again before every pass.

The counter i is what makes the condition become False. The counter goes 0, 1, 2, 3, 4. When it reaches 5, the check 5 < 5 is False, and the loop ends.

The infinite-loop trap: if you forget i += 1, the condition never changes. This code is shown only to illustrate the problem; do not run it:

i = 0
while i < 5:
    print("still going")
    # i += 1 is missing, so i stays 0 and i < 5 stays True forever

Everyday analogy: asking "Is the belt empty?" again and again without removing any parcels. The answer never changes, so you never stop checking.

Quick questions

Which loop visits every item in a list once, in order?
A for loop. It stops by itself when the list runs out of items.
What does break do inside a loop?
It ends the loop immediately. Code after the loop still runs.
After continue runs, does the loop end?
No. It skips the rest of that pass and moves on to the next item.
✎ Try it yourselfKnowledge check · Practice only

Practice: Predict a loop with continue.

parcels = ["sent", "lost", "sent"] for p in parcels: if p == "lost": continue print(p) What does this code print?

Try the parcel belt simulator.

The belt holds the five parcels from the running example. Each mode is a small loop. Each press of Next item runs one pass.

Try it in this order:

  1. Keep Plain loop and press Next item five times. Each pass prints one parcel.
  2. Choose Count sent. Watch the count change only on passes where the item is "sent".
  3. Choose Break at lost. Press Next item until the loop stops. Notice that the parcels after the lost one are never visited.
  4. Choose Continue past returned. Notice that the returned parcel is skipped and the loop still reaches the last sent.
  5. Press Reset, then try a mode again and see the same output each time.

Toy simulator: it runs the same rules as the code shown here. It is not a live Python interpreter, and the parcel values are invented.

Loop to run
  1. "sent"next
  2. "lost"not visited
  3. "sent"not visited
  4. "returned"not visited
  5. "sent"not visited
for p in parcels:
    print(p)
Printed so farnothing yet

Press Next item to run pass 1.

✎ Try it yourselfKnowledge check · Practice only

Check your understanding.

parcels = ["sent", "lost", "sent"] count = 0 for p in parcels: if p == "sent": count += 1 print(count) What does this code print?
THE TAKEAWAY

Take this with you.

  • for item in list: the body runs once per item, in order. The loop variable holds the item, not its position.
  • Accumulators: set the variable before the loop and update it inside, such as count += 1.
  • break and continue: break ends the loop; continue skips the rest of one pass.
  • while: the condition is checked before every pass. Change something inside the body, so the condition eventually becomes False or you leave with break.
Back to Chapter P1 →