Give a task a reusable name
A function groups instructions under a name. Define it with def, accept needed values as parameters, and return a result when the caller needs to use it. A function should have one clear responsibility.
Keep a program understandable
Choose descriptive names and split a long task into a few small steps. Test a function with normal, boundary, and invalid values. Returning a result makes the behavior easier to reuse than printing from deep inside the function.
Try it
Write a function that accepts a price and quantity and returns their product. Test a normal order and a quantity of zero. Add a short comment only where the purpose is not clear from the code.
Key takeaways
- Functions package reusable behavior.
- Parameters provide input and return provides output.
- Test normal, boundary, and invalid cases.