Learn Python · lesson 20 of 60 · about 8 minutes
Running Totals and Nested Loops
Add up how long Sam's tasks will take: keep a running total inside a loop, and put one loop inside another.
What you'll learn
- Keep a running total
- Count items that match
- Write nested loops
How long is today?
Sam wants to know how long today's tasks will take altogether. The assistant can ask for the minutes of each task, but it has to keep adding them up as it goes, then show the total as hours and minutes.
The running total pattern
Start a variable at 0 before the loop, then add to it inside the loop. After the loop it holds the total. This pattern appears in almost every real program.
Adding 1 to 5
total = 0
for n in range(1, 6):
total += n
print(total)Output
15Minutes for every task, then the total
tasks = 3
total = 0
for number in range(1, tasks + 1):
minutes = int(input(f"Minutes for task {number}? "))
total += minutes
print(f"Busy for {total // 60} h {total % 60} min")
Output
Minutes for task 1? Minutes for task 2? Minutes for task 3? Busy for 1 h 35 minLoops inside loops
A loop can sit inside another loop. For every single pass of the outer loop, the inner loop runs all the way through.
Every pair
for row in range(1, 3):
for col in range(1, 4):
print(row, col)Output
1 1
1 2
1 3
2 1
2 2
2 3A small grid of stars
for row in range(3):
line = ""
for col in range(4):
line += "*"
print(line)Output
****
****
****Tip
input() always gives text. Turn each answer into a number with int() before adding it, or += tries to add text to a number.
Now try it yourself
This lesson is free in Codiqo, with 10 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.