← Back to course
Code Crew G5 / Week 05 / Tuesday
2/6
Week 05 Β· Loop or recursion?

Tuesday

Adding up two ways
// The same job, two ways
⏱ about 15 min

Tuesday: Adding up two ways

Last week the fleet stacked fuel cells in a triangle. sum_to(4) said 10 cells.

Today the triangle has 6 rows. Rocket calls sum_to(6). Raven wants to check it with a loop.

"But my loop needs a list of numbers," Raven says. "I only have the number 6."

Rocket asks, "What do you notice about the numbers we add?"

Nova lines up glowing dots. "Here is a hint. Python has a tool that makes a run of numbers for you."

range makes a run of numbers

range(1, 5) makes the numbers 1, 2, 3 and 4. It starts at the first number. It stops just before the second number.

So range(1, n + 1) gives every number from 1 up to n.

print(list(range(1, 5)))
print(list(range(1, 7)))
Output:
[1, 2, 3, 4]
[1, 2, 3, 4, 5, 6]
What is the last number in range(1, 9)?
How many numbers are in range(1, 11)?

The same total, two ways

def sum_to(n):
    if n == 0:
        return 0
    return n + sum_to(n - 1)

def sum_to_loop(n):
    total = 0
    for i in range(1, n + 1):
        total = total + i
    return total

print(sum_to(4), sum_to_loop(4))
print(sum_to(6), sum_to_loop(6))
Output:
10 10
21 21
What does sum_to_loop(7) return?
WHY THIS EXERCISEBoth versions add every number from 1 to n, so they always agree.
COMPARE THE TWO VERSIONS.
  • Read the question.
  • Tap your answer.
Which version starts adding from the biggest number?
In sum_to_loop, what does total start at?

Practice lab: more ranges

print(list(range(3, 7)))
print(list(range(0, 4)))
total = 0
for i in range(1, 4):
    total = total + i * 2
print(total)
What is the first number in range(3, 7)?
How many numbers are in range(0, 4)?
What does the last line print?
What is the last number in range(5, 10)?
RANGE CHECK
  • Read the question.
  • Tap your answer.
Which range gives 1, 2, 3, 4, 5?
What is list(range(2, 4))?
In sum_to_loop, what does the loop add each pass?
StatementTrue or false?
range(1, n + 1) includes n.?
range(1, 4) includes 4.?
sum_to(5) and sum_to_loop(5) both return 15.?
A for loop over range(1, 4) runs 3 times.?
WHY THIS EXERCISEKnowing exactly what range makes keeps loops from running one time too few.
What does sum_to_loop(10) return?
WHY THIS EXERCISEThe loop adds every number from 1 to 10.

Great checking! Two programs that agree give us more confidence. Tomorrow we turn a loop into a recursion on purpose.

← Monday