Loops Plus Decisions
Combine for loops with if to do real work
Loops become genuinely useful when you put an if inside them. Now your program can examine every item and react differently to each.
Sorting numbers as they go by
numbers = [4, 7, 10, 3, 8]
for n in numbers:
if n >= 7:
print(n, "is big")
else:
print(n, "is small")The loop visits each number, and the if decides what to say about it. Look at the indentation: the if is indented once because it's inside the loop, and the print lines are indented twice because they're inside the if. Indentation is how Python keeps track of what belongs where.
Keeping a running total
A common pattern is building up a result as you loop. Start with a variable, then add to it each time around:
numbers = [4, 7, 10, 3, 8]
total = 0
for n in numbers:
total = total + n
print("The total is", total)Each pass, total = total + n means "make the new total equal to the old total plus this number." We start at 0 and grow it. By the end, total holds the sum of everything.
Tip: The pattern of starting a variable before the loop and updating it inside the loop is everywhere in programming — for counting, totalling, and finding the biggest or smallest. Get comfortable with it.
Your turn
Change the numbers in the list and watch both the labels and the total change.
Press “Run code” to see the result.
Quick check
Q1 In the totalling example, why do we write total = 0 BEFORE the loop?
Q2 In for n in numbers: with an if inside, why are the print lines indented twice?
Want to save your progress? It's free.
Create a free account