Python Fundamentals ยท Functions
Names made inside a function live only during the call. Read a global from inside a function, and change one with the global keyword.
rate = 0.1 # global: visible everywhere in the file
def price_with_tax(price):
tax = price * rate # tax is local: it exists only during this call
return price + tax
def raise_rate():
global rate # without this, rate = ... would make a new local name
rate = 0.2
before = price_with_tax(100)
raise_rate()
after = price_with_tax(100)
print(before, after)price_with_tax(). Its body does not run yet: it runs each time the function is called.raise_rate(). Its body does not run yet: it runs each time the function is called.price_with_tax(), with price = 100. It gets its own names.tax is a local name. rate is not local, so Python finds the global one.tax disappears.price_with_tax() has finished, so its names are gone. The value it returned, 110, is stored in before.raise_rate().global rate tells Python that rate = 0.2 means the global name, not a new local one.raise_rate().tax is created with the value 20.price + tax.