Names stay inside
Know that each function has its own boxes, and that numbers are copied when you pass them in. About 9 minutes.
Every function has its own boxes
Think of two classrooms in a school. Each has its own monitor, and both monitors may be called Sam. Nobody gets confused, because each Sam belongs to a different room.
Functions work in the same way. A variable made inside a function belongs to that function, and it disappears when the function ends. Another function can have a box with the same name, and the two never clash. That is why you can use n or total or count in every helper you write.
Numbers are copied in
When you call a helper and give it a number, the helper gets a copy of the number, not your original box. If the helper changes its copy, your original stays exactly as it was.
That is why our halving helper can safely count n down to 0. The caller's number is untouched. It also means a helper can't change a caller's variable by accident. If you want something back from a helper, you have to return it.
def halvings(n):
count = 0
while n > 0:
n = n // 2
count = count + 1
return count- a
- 10
The caller has a box called a holding 10.
A helper takes a number n and counts it down to 0 inside. The caller passed in its own variable a, which held 10. What does a hold after the call?
- A10
- B0
- C4
Show the answer
10. The helper worked on a copy. The caller's a is untouched.
Halving report
Write a helper that counts how many times a number can be halved (whole-number division) until it reaches 0. Return a list of four numbers: the halvings of a, the halvings of b, then a and b themselves, exactly as they were given.
a = 10, b = 3 → [4, 2, 10, 3]
0 ≤ a, b ≤ 2,000,000,000