Functions
What Are Functions?
A function is like a recipe card. You write the instructions once, give it a name, and whenever you need that dish, you just call the recipe by name. You can even customize it — "make this recipe but with extra cheese" (that's a parameter!).
Functions help you:
- Avoid repetition — Write code once, call it many times.
- Organize — Break complex programs into manageable pieces.
- Test — Easier to test one small function than a massive script.
Defining & Calling Functions
Parameters Deep Dive
Python gives you incredibly flexible ways to pass data into functions:
- Positional args — matched by position:
greet("Alice", 25) - Keyword args — matched by name:
greet(name="Alice", age=25) - Default values — optional parameters with fallbacks:
def greet(name, greeting="Hello") *args— Collects extra positional arguments into a tuple**kwargs— Collects extra keyword arguments into a dictionary
*args and **kwargs
Scope — Where Variables Live
Variables created inside a function are local — they live on the call stack and exist only while the function is running, then vanish. Variables created outside functions are global — they stick around for the whole program.
Think of it like this: local variables are written on a whiteboard in a meeting room. When the meeting's over, the whiteboard gets erased. Global variables are written on the office wall — everyone can see them, but changing them from inside a meeting room requires special permission (global keyword).
Scope & Returning Multiple Values
Docstrings — Document Your Functions
A docstring is a triple-quoted string right after the def line. It describes what the function does, what it takes, and what it returns. It's not just a comment — Python actually stores it and you can access it with help().