Functions
Functions are the building blocks of organized code. They let you name a block of code and reuse it whenever you need it.
Why Functions?
Without functions, you'd copy-paste the same code every time you need it. Functions solve this by letting you:
- Write once, use many times
- Give a name to a complex operation
- Break big problems into small, manageable pieces
Anatomy of a Function
Every function has:
- A name that describes what it does
- Parameters (inputs) — data the function needs to do its work
- A body — the code that runs when the function is called
- A return value (output) — the result the function gives back
Parameters vs Arguments
- Parameter: The variable name in the function definition (the placeholder)
- Argument: The actual value you pass when calling the function
Return Values
return sends a value back to the code that called the function. Once a function hits return, it stops executing immediately.
A function without a return value is called a void function — it performs an action (like printing) but doesn't produce a result you can store.
Scope
Variables created inside a function are local — they only exist inside that function. They're created when the function runs and destroyed when it finishes. This prevents different parts of your program from accidentally interfering with each other.
Try It Yourself
- Write a function that converts Celsius to Fahrenheit:
F = C * 9/5 + 32 - Write a function that takes a list of numbers and returns the largest one
- Create a function that checks if a string is a palindrome