Default and keyword arguments
🌍 In real life. At a tea stall, "tea" means tea with sugar unless you say otherwise: sugar is the default. And a form that says "Name: ___ City: ___" can be filled in any order, because each blank has a label.
Python parameters can have defaults, and arguments can be given by their labels.
The idea in one sentence: a parameter with a default value can be left out of a call, and a keyword argument like greeting="Hi" names the parameter it's for, so order doesn't matter.
Its words:
- default value:
def greet(name, greeting="Hello"):; used when the call gives nothing - keyword argument: an argument given by name,
greeting="Hi" - positional argument: an argument matched by its place, like before
Step by step, for greet("Ana"):
"Ana"is the first value, sonamegets it.- Nothing is given for
greeting, so it uses its default,"Hello". - The function returns
Hello, Ana!.
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
print(greet("Ana"))
print(greet("Bo", "Hi"))You can also give arguments by name, like greeting="Hi". These are keyword arguments, and with them the order doesn't matter. Named arguments must come after the plain ones.
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
print(greet(greeting="Hi", name="Bo"))You've been using keyword arguments all along! print has two: sep (what goes between the values) and end (what goes at the end).
print("a", "b", "c", sep="-")
print("no new line", end="!")
print()How Python matches them. First the positional arguments fill parameters from the left; then each keyword argument fills the parameter it names; then any parameter still empty takes its default. If one is still empty after that, it's an error.
Mistakes and edge cases.
- A default before a plain parameter.
def f(a=1, b):givesSyntaxError: parameter without a default follows parameter with a default. - A positional after a keyword.
f(a=1, 2)givesSyntaxError: positional argument follows keyword argument. - A misspelt keyword.
greet(nme="Bo")givesTypeError: greet() got an unexpected keyword argument 'nme'. Did you mean 'name'? - The same parameter twice.
greet("Ana", name="Bo")givesTypeError: greet() got multiple values for argument 'name'. - A list as a default.
def add(x, items=[]):makes the list once, when the function is defined, so every call shares it:add(1)thenadd(2)gives[1, 2]. Useitems=Noneand make a new list inside.
Quiz
What does this print?
def power(base, exp=2): return base ** exp print(power(3), power(2, 3))What does this print?
def minus(a, b): return a - b print(minus(b=1, a=10))What does this print?
print(1, 2, 3, sep=", ")With
def f(a, b=0):, which call does Python refuse?- f(b=1, 2)
- f(2)
- f(2, b=1)
Which line has a mistake?
def make(size=1, color): return color * size print(make(2, "x"))
Coding tasks
Write
power(base, exp=2)that returnsbaseto the powerexp. With noexp, it squares.Write
greet(name, greeting="Hello")that returns a string likeHello, Ana!.Write
make_line(n, char="-")that returns a string ofncopies ofchar.