A function is a named block of reusable code. Define it with def.
Parameters and return
def add(a, b): return a + b- Without
return, a function returnsNone - Return several values:
return x, y(a tuple)
Kinds of arguments
- Positional:
greet("Asha", 21) - Keyword:
greet(age=21, name="Asha") - Default values:
def greet(name, msg="Hello") *args— any number of positional arguments (a tuple)**kwargs— any number of keyword arguments (a dict)
⚠️ Never use a mutable default like def f(items=[]) — the same list is shared between calls. Use None and create the list inside.
Scope
Variables created inside a function are local. Read globals freely; to change one, use global (better: pass values in and return results).
Type hints
def area(w: float, h: float) -> float: — hints help editors and tools; Python does not enforce them.
Docstrings
Describe what the function does in the first line.
Example
Example — Functions with different arguments
Python
def bill(*prices: float, discount: float = 0, **extra) -> float:
"""Return the total after discount, plus any extra charges."""
total = sum(prices) * (1 - discount / 100)
total += sum(extra.values())
return round(total, 2)
print(bill(100, 250, 50))
print(bill(100, 250, 50, discount=10))
print(bill(500, discount=5, delivery=40, packing=10))
def add_item(item, cart=None):
if cart is None: # safe default
cart = []
cart.append(item)
return cart
print(add_item("pen"), add_item("book"))
def min_max(nums):
return min(nums), max(nums)
lo, hi = min_max([4, 9, 1])
print(lo, hi)
Output: 400, 360.0, 525.0, ['pen'] ['book'] (each call gets its own list), 1 9