GCGY Beta v1.0.1
GrowCodeEngineering
← Back to Hub
Back to Topics
python / python-basics
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)) # 64

Demonstrates 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
Continue Path
Challenge: Write a function `calc_avg(*args)` that returns average of passed numbers.
Python Level 4: Functions, *args & **kwargs
1
2
3
4
5
6
7
8
9
10
11
12
13
No test case execution results available yet. Click "Run Code" to evaluate your solution.