Python 3D Academyবাংলা

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"):

  1. "Ana" is the first value, so name gets it.
  2. Nothing is given for greeting, so it uses its default, "Hello".
  3. 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): gives SyntaxError: parameter without a default follows parameter with a default.
  • A positional after a keyword. f(a=1, 2) gives SyntaxError: positional argument follows keyword argument.
  • A misspelt keyword. greet(nme="Bo") gives TypeError: greet() got an unexpected keyword argument 'nme'. Did you mean 'name'?
  • The same parameter twice. greet("Ana", name="Bo") gives TypeError: 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) then add(2) gives [1, 2]. Use items=None and make a new list inside.

Quiz

  1. What does this print?

    def power(base, exp=2):
        return base ** exp
    
    print(power(3), power(2, 3))
  2. What does this print?

    def minus(a, b):
        return a - b
    
    print(minus(b=1, a=10))
  3. What does this print?

    print(1, 2, 3, sep=", ")
  4. With def f(a, b=0):, which call does Python refuse?

    • f(b=1, 2)
    • f(2)
    • f(2, b=1)
  5. Which line has a mistake?

    def make(size=1, color):
        return color * size
    
    print(make(2, "x"))

Coding tasks

  1. Write power(base, exp=2) that returns base to the power exp. With no exp, it squares.

  2. Write greet(name, greeting="Hello") that returns a string like Hello, Ana!.

  3. Write make_line(n, char="-") that returns a string of n copies of char.