Functions are the basic unit of reuse, testing and readable structure in any program.
def defines a function: a name, a parameter list and an indented body. return sends a value back to the caller and ends the function; a function that finishes without return returns None.
Calls can pass arguments positionally or by keyword: area(3, 4) and area(width=3, height=4) are equivalent, and keywords make call sites self-documenting. Parameters can have default values, def greet(name, greeting="Hello"), so callers may omit them. Parameters with defaults must come after those without.
Defaults are evaluated once, when the def statement runs, not on each call. A mutable default like def add(item, bucket=[]) is therefore shared by every call and keeps growing. The idiom is to default to None and create the object inside: if bucket is None: bucket = [].
The first string in the body is the docstring. help(func) shows it and tools read it, so describe what the function does, its arguments and its result.
Variables assigned inside a function are local; they vanish when the call returns and don't clash with names elsewhere. A function can read global names, but assigning to one inside the function creates a new local instead (the global statement changes that, but it is rarely the right design — pass values in and return results).
Good functions do one thing, are short enough to read at a glance, and are named with a verb: parse_line, send_email.
Example
def bmi(weight_kg, height_m, digits=1):
"""Return body-mass index rounded to `digits` places."""
return round(weight_kg / height_m ** 2, digits)
print(bmi(70, 1.75)) # 22.9
print(bmi(height_m=1.8, weight_kg=81, digits=2)) # 25.0
def add_tag(tag, tags=None):
if tags is None: # fresh list per call
tags = []
tags.append(tag)
return tags
print(add_tag("a"), add_tag("b")) # ['a'] ['b']
def nothing():
pass
print(nothing()) # None
print(bmi.__doc__)Remember
- A function without
returnreturns None - Default values are evaluated once at definition time
- Use
Noneas the default for mutable arguments
Watch out for
- Using a mutable default like
[]or{}, which is shared across calls.