Local Variables and Function Scope
What you'll learn: How variables declared inside a function live only within that function and can't be accessed from outside.
The Core Idea
When you declare a variable inside a function, that variable is local to that function. It exists only while the function is running and is completely invisible to code outside the function—including other functions or the main program.
Think of a function like a workshop with its own private toolbox. Tools (variables) you bring into that workshop stay there. Once you leave the workshop (the function finishes), those tools disappear. Other workshops (other functions) can't reach in and grab your tools.
Why This Matters
Local variables prevent conflicts. Two functions can each have a variable named count without interfering with each other, because each count lives in its own isolated scope.
def calculate_total():
price = 50 # local to calculate_total
return price * 2
def apply_discount():
price = 100 # different variable, local to apply_discount
return price * 0.9
result = calculate_total() # works fine, returns 100
# print(price) # ERROR! price doesn't exist here
Each function has its own price variable. They don't conflict because each is local to its function. Trying to access price outside either function causes an error—it simply doesn't exist in that outer scope.
Function Scope Boundaries
The function's curly braces or indentation block defines its scope boundary. Variables created inside cannot escape. Parameters (from the parameter list) are also local variables—they exist only inside the function.
Key Takeaway: Variables declared inside a function are local to that function—they exist only during execution and are inaccessible from outside, preventing naming conflicts and keeping functions self-contained.