Lesson 26/48 ยท โš™๏ธ Functions
โš™๏ธ FunctionsLesson 26/48
Phase 4 ยท Functions22 min

Functions, kwargs, *args & Defaults

Keyword arguments, default values, and accepting any number of inputs

You've learned to define functions with parameters. Now let's make them smarter and more flexible, with default values, keyword arguments, and variable-length inputs.
Default parameters, optional arguments with fallback values
Give a parameter a default value using = in the function definition:
Default parameter valuespython
def greet(name, greeting="Hello"):
    print(f"{greeting}, {name}!")

greet("Alice")            # Hello, Alice!   (uses default)
greet("Bob", "Hi")        # Hi, Bob!        (overrides default)
greet("Carol", greeting="Hey")  # Hey, Carol!
Rule: Parameters with defaults must come AFTER parameters without defaults. def f(a=1, b) is a SyntaxError.
Keyword arguments, call by name, not position
You can pass arguments in any order if you name them:
Keyword argumentspython
def make_coffee(size, strength, milk=False):
    print(f"{size} {strength} coffee, milk: {milk}")

# Positional (order matters)
make_coffee("large", "strong")

# Keyword (order doesn't matter)
make_coffee(strength="mild", size="small", milk=True)
๐Ÿค”Quick Check

Given def power(base, exp=2), which call returns 8?

*args, accept any number of positional arguments
The *args syntax packs all extra positional arguments into a tuple:
*args for variable argumentspython
def add_all(*numbers):
    return sum(numbers)

print(add_all(1, 2, 3))        # 6
print(add_all(10, 20, 30, 40)) # 100
**kwargs, accept any number of keyword arguments
The **kwargs syntax packs extra keyword arguments into a dictionary:
**kwargs for named argumentspython
def describe(**details):
    for key, value in details.items():
        print(f"  {key}: {value}")

describe(name="Alice", age=30, city="London")
# name: Alice
# age: 30
# city: London
๐Ÿค”Quick Check

Inside a function defined as def f(*args), what type is args?

Practice Exercises

0/3 solved
Exercise 1 of 3easyGuided
โฑ 00:00

Flexible Greeter

Write a function greet(name, title="", punctuation="!") that prints a greeting.
- greet("Alice") โ†’ Hello, Alice!- greet("Smith", title="Dr.", punctuation=".") โ†’ Hello, Dr. Smith.
solution.py
1 / 3
Exercise 2 of 3easy
โฑ 00:00

Sum Any Numbers

Write a function total(*nums) that returns the sum of any number of arguments.
- print(total(1, 2, 3)) โ†’ 6- print(total(10, 20)) โ†’ 30
solution.py
2 / 3
Exercise 3 of 3medium
โฑ 00:00

Profile Builder

Write a function build_profile(name, **info) that prints a profile card.
Call: build_profile("Alice", age=30, city="London", job="Engineer")
Expected output:Profile: Aliceage: 30city: Londonjob: Engineer
solution.py
3 / 3
Solve all 3 exercises to unlock completion