This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 5: Advanced function features

Default arguments

face Josiah Wang

Python also allows you to provide default arguments, so that the poor user (that includes you!) does not have to explicitly provide a value for every single parameter.

def do_something(a, b, c=2, d="great", e=5, f="john", g="python", h=-1, i=0, j=2):
    print(f"{a}; {b}; {c}; {d}; {e}; {f}; {g}; {h}; {i}; {j}")
    return None

Users calling the function must provide the first two positional arguments. Then they can optionally provide any additional arguments that they need. Anything else not given will use the default arguments that the function defined.

>>> x = do_something("first", "second")
first; second; 2; great; 5; john; python; -1; 0; 2

>>> x = do_something("first", "second", "arg for c", "arg for d")
first; second; arg for c; arg for d; 5; john; python; -1; 0; 2

The following function definition is not allowed. Why?

def my_function(a="first", b, c, d="default d"):
    print(f"{a}; {b}; {c}; {d}")

Try it out! It will result in a syntax error. The error message should tell you exactly why.