Functions: Reusable Recipes
Name a set of instructions so you can use them again without rewriting them
Imagine you make a great pasta sauce. You don't want to remember every step every time you cook it โ you write down the recipe once. Next time, you just say "make the pasta sauce." Functions are named recipes. Write the steps once, use them anywhere.
A function is a named recipe
Your recipe book has a page called "Bolognese Sauce." It lists: ingredients (inputs), steps to follow, and what comes out at the end (output). You can make Bolognese whenever you want by calling the recipe by name. You can give it different inputs (beef vs pork) and get slightly different outputs. A programming function works identically โ it has a name, it takes inputs (called arguments or parameters), it does steps, and it returns an output.
The anatomy of a function
Every function in every language has the same four parts โ just written differently:
Function anatomy โ same idea, two languages
// JavaScript
function greet(personName) {
let message = "Hello, " + personName + "!"
return message // the output
}
greet("Sarah") // โ "Hello, Sarah!"
greet("Alex") // โ "Hello, Alex!"
# Python โ identical concept, different syntax
def greet(person_name):
message = "Hello, " + person_name + "!"
return message
greet("Sarah") # โ "Hello, Sarah!"Why functions exist
- Write once, use anywhere โ Instead of writing the same 10 lines of code 20 times, write the function once and call it 20 times.
- Give complex things simple names โ "calculateTax(price)" is easier to read than the 15 lines of maths it contains.
- Test one thing at a time โ You can test a function independently to make sure it works before using it in a bigger program.
- Change in one place โ If the tax calculation changes, update the function once โ every place that calls it gets the update automatically.
Real-world functions you use every day
Google Search is a function: input = your query, output = a list of results. A bank transfer is a function: inputs = from account, to account, amount; output = confirmation number. Every button on a website calls a function. You've been using functions for years โ now you're going to write them.
Try this
Write a "recipe" in plain English for calculating a restaurant bill: inputs are (meal cost, number of people, tip percentage). Steps: calculate total with tip, divide by number of people. Output: amount each person pays. That's a function. You just designed one without any code.