Syllabus Lesson 22 of 239 · Functions
Functions

Default and Keyword Arguments

You can give a parameter a default value. If the caller skips it, the default is used:

def greet(name, greeting="Hello"):
    return f"{greeting}, {name}!"

print(greet("Sam"))              # Hello, Sam!
print(greet("Sam", "Hi"))        # Hi, Sam!

Parameters with defaults must come after any without defaults in the def line.

When calling, you can also name your arguments. These are keyword arguments, and they make the call clearer and order-independent:

print(greet(name="Ada", greeting="Hey"))   # Hey, Ada!
print(greet(greeting="Hey", name="Ada"))   # same result, order does not matter

You can mix the two styles, but every positional argument must come before any keyword argument:

greet("Ada", greeting="Hey")   # fine: positional then keyword
# greet(name="Ada", "Hey")     # error: keyword before positional

Defaults let you write one flexible function instead of several near-identical ones.

Your turn

Define a function power with parameters base and exp, where exp defaults to 2. It should return base ** exp. So power(5) returns 25, power(2, 3) returns 8, and power(base=3, exp=4) returns 81.

Spotted a problem in this lesson? Report it

Code · runs in your browser
Output