← Learning Hub
Beginner

Functions

A function is a named block of code you can use again and again. Create one with def, and send a result back with return.

Imagine you calculate GST in ten different places in your program. If the rate changes, you'd have to find and fix all ten. With a function, you write the calculation once, give it a name, and call it wherever you need it. Change it in one place, and everything is updated.

Functions also make code easier to understand. A line like with_gst(price) tells you what's happening without reading the maths. Good programs are built from many small functions, each doing one clear job.

The values you pass in are called arguments; the names that receive them (price) are parameters. return sends the answer back to whoever called the function. A function without return gives back None.

Example
You can edit this code.

Default and keyword arguments

Example
You can edit this code.

A default value makes a parameter optional: if the caller doesn't give a discount, 10 is used. Keyword arguments (discount=50) let you name the values, so the order doesn't matter and the call is easier to read - especially when a function has many parameters.

Returning more than one value

Example
You can edit this code.

Lambda: a tiny one-line function

Example
You can edit this code.

A lambda is a small function without a name, written in one line. It's mostly used where a function is needed only once - like telling sort what to sort by. Here lambda pair: pair[1] means "sort each pair by its second value, the price".

A variable made inside a function only exists inside that function.
Key points
  • Define with def name(parameters): and send a result back with return.
  • Write once, use many times - and fix bugs in one place.
  • Default values make parameters optional; keyword arguments make calls clearer.
  • Variables created inside a function stay inside it.

📝 Test yourself

1. Which keyword creates a function?
2. What does a function give back if it has no return?
3. Fill in the keyword that sends a value back from a function:
total