Variables created inside a function only exist inside that function. Once it returns, they're gone.
def calc():
temp = 42
return temp * 2
result = calc()
print(result) # 84
print(temp) # NameError — temp doesn't exist out here
It means a function is a self-contained box. Whatever it does inside can't accidentally rename or corrupt a variable you have outside. Imagine the alternative — every function in a million-line program clobbering each other's variables.
TAX_RATE = 0.08 # global constant
def add_tax(amount):
return amount * (1 + TAX_RATE) # OK to read
# Bad pattern — reaching outside to change a global
TOTAL = 0
def add(n):
global TOTAL
TOTAL += n
# Good pattern — return the new value, let the caller decide
def add(total, n):
return total + n
A clean function takes its inputs as parameters and gives its output as a return value. It doesn't reach out into the world. It's predictable, testable, and reusable. Treat global like cigarettes — legal, occasionally unavoidable, mostly a sign you should reconsider.
global for assignment.RUNNING_TOTAL = 0
def add_invoice(amount):
global RUNNING_TOTAL
RUNNING_TOTAL += amount
return RUNNING_TOTAL
Rewrite without the global. Pass the running total in, return the updated value.