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

Keyword arguments

face Josiah Wang

Here is our function definition again.

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

A caller can also use keyword arguments to supply the arguments for these optional parameters without worrying about the positioning of the parameter. The caller can skip any optional parameters arbitrarily.

>>> x = do_something("first", "second", i=2, f="josiah")
first; second; 2; great; 5; josiah; python; -1; 2; 2

In fact, using keyword arguments in your function calls can potentially improve the readability of your code. Compute the two function calls below. They both do the same thing, but which one do you find more self-explanatory and easier to understand?

robot = generate_robot(3, 6, "joy", 100, 200, True)

robot = generate_robot(x=3, y=6, message="joy", width=100, height=200, random=True)