Addaly is in open beta. Things will change, and AI answers can be wrong — check anything that matters.

Loops, or doing the same thing to many things

Python, From Zero, For AI · lesson 5 of 10 · 6 min

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)
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)}")

Before you move on

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. Nobody sees your answer.

No ads. No data sale. No public scores on people. Ever.

© 2026 Addaly