Breaking problems into functions
A function is a named, reusable block of code that does one job. Functions are how programmers tame complexity: big problems become a set of small, testable pieces.
Defining and calling a function
nameis a parameter: the function's input."Asha"is an argument: the actual value passed in.returnsends a result back to whoever called the function.
Think of a function as a machine: inputs → work → output.
Why use functions?
- Reuse: write once, use everywhere.
- Readability:
calculate_tax(order)explains itself. - Testing: small functions are easy to check one at a time.
- Change in one place: fix a bug once, not in ten copies.
DRY: Don't Repeat Yourself. If you copy-paste code for the third time, turn it into a function.
Decomposition: top-down problem solving
Problem: "Print a receipt for a shopping cart, with a 10% discount on orders over ₹1000 and 18% tax."
Don't write it as one giant block. Name the steps first, then write each as a function:
Each function is tiny and obvious. print_receipt reads like the problem statement. That's good design.
Return vs print
A common beginner mistake is printing inside a function instead of returning. Printed values can't be reused:
Scope: variables live inside their function
Local variables keep functions independent, so they don't interfere with each other.
Default and named arguments
Good function habits
- One job per function. If you need "and" to describe it, split it.
- Name it with a verb:
calculate_total,is_valid_email,send_invite. - Keep it short: usually under 20–30 lines.
- Prefer returning values over changing global variables.
Practice
Decompose this problem into at least three functions: "Given a list of exam scores, print the average, the highest score, and the grade (A ≥ 90, B ≥ 75, C ≥ 50, otherwise F) for the average."
1.What's the difference between a parameter and an argument?
2.Why is returning a value usually better than printing inside a function?