How it works
Names assigned inside a function are local unless declared otherwise. Reading an outer name works; assigning to it creates a new local one.
Pass values in and return them out rather than reaching for globals.
Common error
Assigning to a name that also exists outside, which creates a local and leaves the outer one untouched.
Worked example
Python
count = 10
def local_count():
count = 3
return count
print(local_count())
print(count)Output
3
10The assignment inside the function creates a local binding. It does not reassign the module-level name in this example.
Exercises
2.3.1 · Trace
Determine the exact output and explain the state changes.
Python
x = 5
def f(x):
x += 1
return x
print(f(x), x)Show solution
Output
6 5The parameter x is local, and incrementing that local integer binding does not change the caller binding.
2.3.2 · Explain
Why is returning a value often clearer than changing a global variable?
Show solution
It makes the dependency and result explicit at the call site, reducing hidden shared state and simplifying isolated tests.
