Hone

Lessons · Python · where a variable lives

Where a name lives

A variable made inside a function exists only there. Names from outside can be read, but assigning creates a new local one.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

The 'UnboundLocalError' and the 'why did my counter not change' mysteries both come from scope. Once it clicks, both vanish.

How to think about it

Ask: where was this name first assigned? Inside the function, it is local to that call. If you need to change something outside, return the new value and let the caller store it.

Worked example

count = 0
Module level.
def bump():
A function that needs the outer value.
    return count + 1
Reading the outer name is fine.
count = bump()
The caller stores the new value. Clean.

Your turn

Make the function give back a new total rather than change the outer one.

def add(total, n):
     total + n

The trap

Writing count += 1 inside a function makes count local, then reads it before assignment: UnboundLocalError. The fix is not 'global'; it is return.

Practise where a variable lives on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.