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.
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:
- Loop variable and body: in
for p in parcels:,pis the loop variable. It holds one item per pass. The indented lines under the colon are the body, which runs once per pass. - Accumulator: a variable you set before the loop and update inside it, such as a running count.
- break: stops the whole loop at once.
- continue: skips the rest of the current pass and moves on to the next item.
- while loop and condition: a loop that repeats while a condition is
True. In this lesson a condition is a test such asi < 5, which givesTrueorFalse. - Infinite loop: a loop whose condition never becomes
Falseand whose body never runsbreak, so it never stops on its own.
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
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) # 3count += 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
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
# sentCommon 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
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 foreverEveryday 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
forloop. It stops by itself when the list runs out of items. - What does
breakdo inside a loop? - It ends the loop immediately. Code after the loop still runs.
- After
continueruns, does the loop end? - No. It skips the rest of that pass and moves on to the next item.
Practice: Predict a loop with continue.
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:
- Keep Plain loop and press Next item five times. Each pass prints one parcel.
- Choose Count sent. Watch the count change only on passes where the item is
"sent". - Choose Break at lost. Press Next item until the loop stops. Notice that the parcels after the lost one are never visited.
- Choose Continue past returned. Notice that the returned parcel is skipped and the loop still reaches the last sent.
- 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.
- "sent"next
- "lost"not visited
- "sent"not visited
- "returned"not visited
- "sent"not visited
for p in parcels:
print(p)nothing yetPress Next item to run pass 1.
Check your understanding.
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:
breakends the loop;continueskips the rest of one pass. - while: the condition is checked before every pass. Change something inside the body, so the condition eventually becomes
Falseor you leave withbreak.