Skip to content

Latest commit

 

History

History
41 lines (30 loc) · 2.56 KB

File metadata and controls

41 lines (30 loc) · 2.56 KB

Function Parameters and Arguments

We tend to use parameters and arguments interchangeably, but they aren't quite the same. Parameters are the empty slots you define in your function signature. Arguments are the actual values you throw into those slots when you call the function. When Python executes the function, it binds your argument to the parameter name, treats it like a local variable, and throws it away once the function is done.

Positional arguments are simple but fragile. If a function expects (width, height) and you pass (1080, 1920) instead of (1920, 1080), Python won't complain, it will just silently run with the wrong values.

Keyword arguments solve this by letting you write width=1920, height=1080. The order no longer matters, and the code is suddenly self-documenting. The only downside is that if you rename a parameter in your function, you have to find and update every single call. Usually, positional arguments are fine for two or three obvious inputs, but keywords are a lifesaver once your function starts growing.

You can mix both in a single call, but positional arguments always have to go first. You can also make parameters optional by giving them default values. If the caller skips them, Python falls back on your default.

Then there are *args and **kwargs for when you don't know what is coming. A single asterisk (*args) grabs any leftover positional arguments and stuffs them into a tuple, which is great for handling lists of similar items. A double asterisk (**kwargs) takes any leftover keyword arguments and turns them into a dictionary, which is incredibly useful for passing around dynamic configurations or settings.

# 'width' and 'height' are PARAMETERS (the empty slots)
def calculate_area(width, height):
    return width * height

# 1920 and 1080 are ARGUMENTS (the actual data thrown into the slots)
result = calculate_area(1920, 1080)
# Function with a default value making 'units' optional
def create_window(width, height, units="pixels"):
    print(f"Creating window: {width}x{height} {units}")

# ---- Positional Arguments (Fragile!) ----
# If you meant width=1920, height=1080, this is a silent bug:
create_window(1080, 1920)
# Output: Creating window: 1080x1920 pixels

# ---- Keyword Arguments (Self-Documenting) ----
# Order doesn't matter anymore
create_window(height=1080, width=1920)
# Output: Creating window: 1920x1080 pixels

# ---- Mixing them + Using Defaults ----
# Rule: Positional arguments MUST come first!
create_window(1920, 1080, units="inches")
# Output: Creating window: 1920x1080 inches