Python Fundamentals ยท Functions

Scope: Local and Global Names

Names made inside a function live only during the call. Read a global from inside a function, and change one with the global keyword.

scope.py

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)

Step by step

  1. A global name: defined at the top level of the file.
  2. Python defines the function price_with_tax(). Its body does not run yet: it runs each time the function is called.
  3. Python defines the function raise_rate(). Its body does not run yet: it runs each time the function is called.
  4. Python calls price_with_tax(), with price = 100. It gets its own names.
  5. Inside the call: tax is a local name. rate is not local, so Python finds the global one.
  6. The call ends and its local tax disappears.
  7. price_with_tax() has finished, so its names are gone. The value it returned, 110, is stored in before.
  8. Line runs: raise_rate().
  9. global rate tells Python that rate = 0.2 means the global name, not a new local one.
  10. Line runs: raise_rate().
  11. Call again: now the global rate is 0.2.
  12. tax is created with the value 20.
  13. The function returns price + tax.
  14. Call again: now the global rate is 0.2.
  15. 110 before, 120 after. Locals live only inside their call; globals are shared, which is why changing them is risky.