Functions and Objects · Functions · lesson 4 of 10
Scope
about 12 minutes · free · runs in your browser
Where a name is visible
A name created inside a function exists only inside it:
def f():
inside = 1 # local to f
f()
print(inside) # NameError
Functions can read names from the surrounding module, but assigning to one creates a new local name rather than changing the outer one:
count = 0
def bump():
count = count + 1 # UnboundLocalError
Python decides at compile time that count is local — because the function assigns to
it — and then finds it has no value yet. The global keyword overrides that, but reaching
for it is nearly always a sign the function should take an argument and return a result
instead.
Mutating is different from assigning: a function can call .append() on an outer list,
because that changes the object rather than rebinding the name.
Your turn: write bump(counter) that returns the counter plus one, without touching
any global. Then use it to bring total to 3.
You start from this, and edit it in the browser:
total = 0
def bump(counter):
# Return the counter plus one.
pass
# Call bump three times, feeding the result back into total.