Functions and errors
Scope and default values
Goal: Understand local variables and default/keyword arguments · 9 min
Variables created inside a function are local: they exist only during the call and are invisible outside. A local variable with the same name as a global one shadows it without changing it.
Default values make parameters optional: def greet(name, greeting="Hello"). Keyword arguments name the parameter in the call: greet("Ada", greeting="Hi").
Good functions get their inputs via parameters and give results via return, instead of reading and changing global variables.
Worked example: Shadowing
- Global x = 1.
- Inside f, a new local x = 99 is created.
- After the call, the global x is still 1.
x = 1
def f():
x = 99
return x
print(f(), x)Output:
99 1