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 = 0Module level.
def bump():A function that needs the outer value.
return count + 1Reading 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 + nSolve one with the tests running
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.