~/learn/Python · Functions
Functions
Package logic behind a name, with defaults and returns.
why this matters
Functions let you write logic once and reuse it everywhere, which keeps programs short and bugs rare.
def defines a function. Parameters can have defaults, and the function hands a value back with return.
Functions are values: you can pass them to sorted, map or filter. A short throwaway function can be written inline as a lambda.
Note
Never use a mutable default like def f(items=[]) — the list is shared across calls. Use None and create it inside instead.
print vs return
print shows a value; return hands it back. A function without return gives back None.
key takeaways
- def name(args): defines a function.
- return sends a result back.
- Default arguments make parameters optional.
check your understanding
def double(x): print(x * 2) What is y after y = double(5)?
free practice
Build confidence with a question you can solve without Pro.