Mental model: Think of a function like a private office with its own whiteboard. You can write notes on that board while working inside, but the moment you walk out, the building staff erases it clean. The hallway outside is your global scope: everything written there stays visible to everyone in the building.
Why: You need this separation so a helper function does not accidentally overwrite data used by other parts of your program. If every variable shared one giant space, changing
total for a receipt printer would also change the player's score in the game engine.Local variables
def calculate_tax(price):
tax = price * 0.1
print(f"Tax: ${tax:.2f}")
calculate_tax(50)
print(tax)tax does not exist outside the function.tax was created inside calculate_tax. It is local. Python discards it when the function finishes. You cannot reach it from outside, which keeps your global namespace clean and predictable.Reading globals
high_score = 950
def display_rank():
print(f"Current high: {high_score}")
display_rank()Reading is free. Python checks the local scope first; if it does not find the name there, it falls back to the global scope automatically. You do not need
global for read-only access.Changing globals
level = 1
def advance():
level += 2
advance()
print(level)Watch out: The moment you assign to a name inside a function (like
level += 2), Python treats it as local for the entire body. It never falls back to global. To modify a true global, add the line global level at the top of the function.