Functions name a block of code so you can reuse it, and scope controls where the names inside are visible.
Defining and calling
- A function is a named block of code, defined with
def name():and a:-terminated header. - The indented lines below the header are the body; they run only when you call the function with
name(). - Defining does not run the body; calling does.
Parameters, arguments, return
- Parameter: the name in the definition. Argument: the value passed at the call. Same slot, two words.
returnends the function and hands a value back to the caller; code after it does not run.- No
return(or barereturn) yieldsNone(not0, not""). A function that onlyprints returnsNone.
Passing arguments
- Positional: matched by order, so order is the meaning (
power(2,3)!=power(3,2)). - Keyword: named at the call (
power(base=2, exponent=3)); order does not matter. - Mixing: all positional arguments must come before any keyword arguments.
- Default argument: a fallback used when the caller omits it (
def greet(name, greeting="hello")). Defaults must come after non-default parameters. *argscollects extra positional arguments into a tuple;**kwargscollects extra keyword arguments into a dictionary.
Gotchas
- Mutable default arguments: the default is created once at definition, so
def f(bag=[])shares one list across all calls. Default toNoneand build a new one inside. - Reassigning a global without declaring it makes the name local for the whole function, causing
UnboundLocalError. Useglobalonly when you truly mean to change the global. - Forgetting parentheses:
greetis the function value;greet()runs it.
Scope: name lookup
- Scope: the region where a name is visible. Variables created inside a function are local and vanish when it returns.
- Top-level names are global; functions can read them, but assigning to a name makes it local unless declared
global.
Use a name inside a function
|
Assigned in this function?
/ | \
no yes, no declared
| 'global' 'global'
GLOBAL LOCAL GLOBAL var
scope (set before (assignment
first use) updates it)
Extras
- Docstring: a string as the first line of the body; explains the function, readable via
func.__doc__. - Functions are values: store them, pass them as arguments (a callback), call with
f()vs reference withf. - Cost: calling is O(1) (a stack frame); the real cost is what the body does.