Defining Functions
Why functions?
They let you write code once and reuse it, give a name to a piece of logic, and make programs easier to test.
Syntax
def greet(name, greeting="Hello"):
"""Return a greeting message.""" # docstring
return f"{greeting}, {name}!"
- Parameters are the names in the definition; arguments are the values you pass.
- Without
return, a function returnsNone. - A function can return several values as a tuple:
return low, high.
Ways to pass arguments
- Positional:
greet("Ana") - Keyword:
greet(greeting="Hi", name="Ana") *argscollects extra positional arguments into a tuple.**kwargscollects extra keyword arguments into a dict.
⚠️ The mutable default trap
def add_item(item, items=[]): # ❌ the same list is reused every call!
Use items=None and create the list inside: if items is None: items = [].
💡 Keep functions small and focused: one job per function, named with a verb (calculate_total).
▶️ Runs in the app.
Example
def greet(name, greeting="Hello"):
"""Return a greeting message."""
return f"{greeting}, {name}!"
def min_max(numbers):
return min(numbers), max(numbers) # returns a tuple
def total(*args, **kwargs):
print("args:", args, "kwargs:", kwargs)
subtotal = sum(args)
return subtotal * (1 + kwargs.get("tax", 0))
print(greet("Ana")) # Hello, Ana!
print(greet("Ben", greeting="Hi")) # Hi, Ben!
low, high = min_max([4, 9, 1])
print(low, high) # 1 9
print(total(10, 20, tax=0.1)) # args: (10, 20) kwargs: {'tax': 0.1} / 33.0
def add_item(item, items=None): # safe default
if items is None:
items = []
items.append(item)
return items