Learn with diagrams, code, systems and practical examples.
Functions
Package reusable behavior behind clear inputs and outputs.
Functions help you avoid duplication and give a meaningful name to a unit of work.
Start with the idea
A function can receive parameters, perform work, and return a result. Good functions are small enough to understand and named after what they accomplish.
Small working example
Run this example first. Do not change several things at once; confirm the basic behavior, then experiment.
def calculate_total(price, quantity):
return price * quantity
print(calculate_total(8, 3)) A function can receive parameters, perform work, and return a result. Good functions are small enough to understand and named after what they accomplish.
- Functions name reusable behavior.
- Parameters are inputs.
- return sends a result back to the caller.
24The example is intentionally small. Focus on the chapter’s main idea before adding extra syntax or framework code.
Common beginner mistake
Printing a value inside a function when callers actually need the value returned.
Use return when the result should be reusable by other code; print only when displaying output is the function's job.
Quick recap
- Functions name reusable behavior.
- Parameters are inputs.
- return sends a result back to the caller.
Try it yourself
These are deliberately small. If you can complete them without copying the example, you are ready to continue.
- Write a function that calculates tax.
- Call the same function with three different inputs.