python / python-orientation
16 mins
Python Level 4: Functions, *args & **kwargs
Why This Matters: Unpacking flexible positional (*args) and keyword (**kwargs) arguments allows writing clean Python APIs.
## Modular Functions & Argument Unpacking
Functions are defined using `def`.
```python
def calculate_total(*args, **kwargs):
s = sum(args) # Sum positional tuple
bonus = kwargs.get("bonus", 0) # Read keyword dict
return s + bonus
print(calculate_total(10, 20, 30, bonus=5)) # 65
```
MENTAL MODEL & MEMORY LAYOUT
ARGUMENT UNPACKING:
*args ──► Packs arbitrary positional arguments into a Tuple (10, 20, 30)
**kwargs ──► Packs arbitrary keyword arguments into a Dict {'bonus': 5} COMMON PITFALLS TO AVOID
- Placing default arguments before non-default parameters in function definitions.
Default Keyword Arguments
def power(base, exponent=2):
return base ** exponent
print(power(4)) # 16
print(power(4, 3)) # 64Demonstrates fallback default parameters when optional arguments are omitted.
CONCEPT MASTERY CHECKPOINT
In Python function signatures, what does `*args` collect?
NEXT RECOMMENDED LESSON
Python Level 5: List & Dict Comprehensions
Challenge: Write a function `calc_avg(*args)` that returns average of passed numbers.