This is an archived version of the course. Please see the latest version of the course.

Function arguments

Like in Java, the basic way of calling a function is via positional arguments. That is, assign arguments to parameters by matching their position.

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

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

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

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

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

Keyword arguments

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

x = my_function("first", "second", i=2, f="josiah")

Note that the caller must provide the (mandatory) positional arguments first before supplying any keyword arguments. It is obvious why if you think about it for a bit - Python will be completely confused when trying to match the parameters to the argument!

x = my_function(d="no good", "first", "second")   # Not allowed. Python will tell you so.

Similarly, you cannot define a parameter that is a positional argument after you have declared one with a default argument. So the below is illegal (See the error message. Python tells you exactly that).

def my_function(a="first", b, c, d="default d"):   # Python says no way!
    return None

Arbitrary number of arguments

If you do not know upfront how many arguments will be provided, Python allows you to use an asterisk (*) to indicate that the parameter allows the caller to provide as many arguments as needed for the parameter. Python will “pack” the parameters into a tuple and assign it to your parameter.

def enroll(*courses): 
   print(type(courses))
   for course in courses: 
      print ('Joined course: ', course)

enroll("Probabilistic Inference", "Introduction to Machine Learning",
     "Computer Vision", "Graphics")

Arbitrary number of keyword arguments

Python also allows a function to take a arbitrary number of keyword arguments. You will use double asterisks (**) to indicate this. This time, you will end up with a dict containing (keyword, value) pairs provided by the user. You can then process these pairs as needed. Useful for example when you provide the caller with many customisable options!

def customise_page(**kwargs):
    for key, value in kwargs.items():
        if key == "background":
            set_background(value)
        elif key == "width":
            set_width(value)
        elif key == "avatar":
            set_avatar(value)
        else:
            print("Unknown keyword {key}.")
            return

customise_page(background="red", width=500, avatar="selfie.jpg")