Python Variable Scope, Docstrings and Good Habits
Local Variables in Python
A variable made inside a function is a local variable: it exists only inside that function, and only while the function runs. The part of a program where a name can be used is called its scope.
Think of it like a whiteboard in a hotel room: you can write on it while you stay, and it's wiped when you check out. People down in the lobby can't read it.
def make_total():
total = 10 + 20
print("Inside:", total)
make_total()
print("Outside:", total)Inside: 30 NameError: name 'total' is not defined
Don't be scared of this error! It's saying that outside the function, there's no total. It lived inside make_total(), and it was wiped when the function ended.
The rules
- A variable you create inside a function is local to it.
- Parameters are local too: they only exist inside the function.
- Every call starts fresh. Local variables don't remember anything from the last call.
def visit():
count = 0
count += 1
print("Visits:", count)
visit()
visit()Visits: 1 Visits: 1
Each call makes a brand-new count, starting at 0. That's why it never reaches 2.
The fix: return the value
When the code outside needs a value from inside, return it, and store what comes back:
def make_total():
total = 10 + 20
return total
total = make_total()
print("Outside:", total)Outside: 30
There are two variables called total here: one local, inside the function, and one outside. return carries the value from one to the other.
A variable made inside a function lives only there. Return it to use it outside.