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.
Default and keyword arguments
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
Lambda: a tiny one-line function
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".
- Define with
def name(parameters):and send a result back withreturn. - 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.
