Exit
  1. Learn
  2. Check
  3. Solve
  4. Reflect

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.

A variable lives inside: the function that made it.

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.

To get a result back, return it. Changing the copy does nothing outside.
In code
def halvings(n):
    count = 0
    while n > 0:
        n = n // 2
        count = count + 1
    return count
Calling halvings with a = 10
a: 10
0
n: ?
1
result: ?
2
line
a
10

The caller has a box called a holding 10.

Move 1 of 4