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(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]
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
print(list(range(3, 7)))
print(list(range(0, 4)))
total = 0
for i in range(1, 4):
total = total + i * 2
print(total) | Statement | True 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. | ? |
Great checking! Two programs that agree give us more confidence. Tomorrow we turn a loop into a recursion on purpose.