tips.md basics.html variables.html functions.html loops.html lists.html project.html
// lesson 3

Functions

~/lessons/functions.html

A function is a named, reusable block of instructions. You write the steps once, give them a name, and from then on you can run all of those steps just by calling that name, as many times as you want, without retyping them.

def greet(): print("Hello!") print("Welcome.") greet() # runs both print lines greet() # runs them again

Think of it like a recipe card. You write the recipe once. Every time you want the dish, you don't rewrite the recipe, you just say "make this one" and follow the card. The function is the card, and calling it is telling the kitchen to actually make the dish.

Passing information in

Most useful functions need to work with different values each time, not the exact same thing every time. That's what parameters are for — placeholders in the function's definition that get filled in with real values when you call it.

def greet(name): print("Hello, " + name + "!") greet("Sam") # Hello, Sam! greet("Priya") # Hello, Priya!

Here, name is a parameter — a variable that only exists inside this function, and gets filled in with whatever you pass when you call it. "Sam" and "Priya" are called arguments, the actual values you're plugging into the parameter slot. Same function, same steps, different result each time based on what you feed it.

Getting information back out

Printing something shows it on screen, but it doesn't give the value back to the rest of your program to use. For that, you need return, which hands a value back to whatever called the function so you can store it or use it somewhere else.

def add(a, b): return a + b result = add(3, 4) print(result) # 7

The difference between print and return trips up almost everyone at first. print just displays something to a human looking at the screen. return hands a value back into the program itself, so it can be stored in a variable, passed into another function, used in a calculation, whatever you need. A function can do both, either, or neither.

Why bother

Beyond just saving typing, functions are how you keep a program from turning into an unreadable wall of repeated code. If you find the same handful of lines showing up in three different places, that's usually a sign those lines should become a function instead — write it once, fix bugs in one place instead of three, and give that chunk of logic an actual name that explains what it's for.

That naming part matters more than it sounds like it should. A function called calculateShippingCost tells you what it does before you even read the code inside it. That's the whole game with functions: breaking a big, confusing problem into smaller pieces that each have one clear job.