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().