|
| 1 | +# Day 25: More on Functions - *args & **kwargs |
| 2 | + |
| 3 | +# --- Part 1: *args (Arbitrary Positional Arguments) --- |
| 4 | +# The *args parameter collects all positional arguments into a tuple. |
| 5 | +def sum_all_numbers(*args): |
| 6 | + """Calculates the sum of an arbitrary number of numbers.""" |
| 7 | + print(f"args is a tuple: {args}") |
| 8 | + total = sum(args) |
| 9 | + print(f"The sum is: {total}") |
| 10 | + |
| 11 | +print("--- Using *args ---") |
| 12 | +sum_all_numbers(1, 2, 3) |
| 13 | +sum_all_numbers(10, 20, 30, 40) |
| 14 | +print("-" * 30) |
| 15 | + |
| 16 | +# --- Part 2: **kwargs (Arbitrary Keyword Arguments) --- |
| 17 | +# The **kwargs parameter collects all keyword arguments into a dictionary. |
| 18 | +def create_profile(**kwargs): |
| 19 | + """Creates a user profile from an arbitrary number of key-value pairs.""" |
| 20 | + print(f"kwargs is a dictionary: {kwargs}") |
| 21 | + for key, value in kwargs.items(): |
| 22 | + print(f" {key.capitalize()}: {value}") |
| 23 | + |
| 24 | +print("--- Using **kwargs ---") |
| 25 | +create_profile(name="Alice", age=30) |
| 26 | +create_profile(username="coder_bob", city="New York", occupation="Developer") |
| 27 | +print("-" * 30) |
| 28 | + |
| 29 | +# --- Part 3: Combining *args and **kwargs --- |
| 30 | +# They can be used together in the same function. |
| 31 | +# The order is: regular arguments, *args, **kwargs |
| 32 | +def combined_example(required_arg, *args, **kwargs): |
| 33 | + print(f"Required Argument: {required_arg}") |
| 34 | + print(f"Positional Arguments (*args): {args}") |
| 35 | + print(f"Keyword Arguments (**kwargs): {kwargs}") |
| 36 | + |
| 37 | +print("--- Combining *args and **kwargs ---") |
| 38 | +combined_example("I am required", 1, 2, 3, a=10, b=20) |
0 commit comments