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 matterYou 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 positionalDefaults let you write one flexible function instead of several near-identical ones.
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.
This lesson is locked
Lessons open one at a time. Finish the previous lesson to unlock this one.