~/learn/Python · Functions

Functions

Package logic behind a name, with defaults and returns.

7 min readlesson 11 of 23deflambdadefaults

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.

python · editable
loading editor…

Functions are values: you can pass them to sorted, map or filter. A short throwaway function can be written inline as a lambda.

python · editable
loading editor…

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.