Python, from Zero, for AILesson 16 of 89

Contents

Python, from Zero, for AI

Lesson 16 of 89. Sign in to keep your place.

Module 2 · Collections, loops, and the shape of your data

Loops, or doing the same thing to many things

6 min read

Repeat once per item

Python
prices = [120, 340, 90, 75]

for price in prices:
    print(price)

Read it as an English sentence: for each price in prices, print the price. Python takes the first item, attaches the name price to it, runs the indented block, then takes the second item, and so on until the list runs out.

price is a name you chose. It could be p or amount. It only exists because you named it in the for line, and it gets re-attached to a new value on every pass.

The indentation is the loop body

Python uses indentation the way other languages use braces. Whatever is indented under the for line runs every pass. Whatever is not, runs once, after the loop is done.

Python
for price in prices:
    print("item", price)
print("done")

done prints once. Move it four spaces to the right and it prints four times. Use four spaces, be consistent, and let your editor do it for you. Mixing tabs and spaces produces IndentationError or, worse, code that runs and means something you did not intend.

The accumulator

The most useful pattern in beginner programming: start with an empty answer, add to it on every pass, look at it at the end.

Python
prices = [120, 340, 90, 75]

total = 0
for price in prices:
    total = total + price
print(total)     # 625

The line total = 0 is outside the loop, and this is the whole trick. It has to happen once, before any adding starts. Put it inside the loop and it happens on every pass, wiping out the running total each time, and the answer becomes the last item instead of the sum. That bug produces no error and looks almost identical on screen.

total = total + price can be shortened to total += price. Same thing.

The same pattern builds lists:

Python
doubled = []
for price in prices:
    doubled.append(price * 2)
print(doubled)   # [240, 680, 180, 150]

Counting with range

When you want to do something a fixed number of times rather than once per item:

Python
for i in range(3):
    print("attempt", i)
Text
attempt 0
attempt 1
attempt 2

range(3) gives 0, 1, 2. Three numbers, starting at zero, stopping before three. range(1, 4) gives 1, 2, 3. The stop value is never included, which is deliberate: range(len(prices)) then lines up exactly with the valid positions.

Looping over a dict

Python
student = {"name": "Amara", "city": "Kano", "marks": 81}

for key in student:
    print(key, "->", student[key])

for key, value in student.items():
    print(key, "->", value)

Both print the same thing. .items() hands you the key and the value together, which is usually what you wanted.

while, for when you do not know how many

Python
balance = 5000
months = 0
while balance > 0:
    balance = balance - 1200
    months = months + 1
print(months, "months")   # 5 months

while repeats as long as its condition is true, and checks the condition before each pass. If nothing inside ever makes the condition false, the program runs forever; press Ctrl+C to stop it. Reach for for first. Use while when the number of passes depends on what happens inside.

Try this now

Python
marks = [78, 81, 45, 92, 60]

passed = []
for m in marks:
    if m >= 50:
        passed.append(m)

print(passed)
print(f"{len(passed)} of {len(marks)} passed")
print(f"average {sum(marks) / len(marks)}")

Check your understanding

A program is prices = [120, 340, 90], then a for price in prices: loop whose indented body is total = 0 followed by total = total + price, then an unindented print(total). What is printed?

Pick the one you would defend. Your answer stays private.

Next lesson · 7 minWhile loops, break, and the loop that never ends

Stuck on something?Ask Divya, your AI tutor

How to cite: Addaly (2026) ‘Loops, or doing the same thing to many things’, in Python, from Zero, for AI. Edited by M. Mun. Addaly. Available at: https://addaly.com/learn/python-for-ai/loops (Accessed: 31 October 2026).