Menu

Sub Programs

Parameters

Parameters are the variables named inside a sub program's brackets when it is defined. They are placeholders for the values the sub program will receive when it is called. When you call it, the values inside the call brackets are passed to the parameters in order: first value to first parameter, second to second, and so on.

A sub program can take no parameters, one parameter or several. Its definition shows how many it expects, so a call must supply a value for each one in the right order. The values supplied in a call may also be called arguments; the distinction between the two terms is not needed here.

Parameters are useful because one sub program can handle fresh values on every call. Without them, a sub program cannot be handed new data each time it is called, so it is less flexible. Both procedures and functions can take parameters, so a procedure is not limited to empty brackets.

A function should receive the data it needs through its parameters. It should not use input() inside the function and overwrite a parameter with the user's answer, because then the value passed in is lost and the function is tied to one way of getting data.

def make_label(name, seat):
    print(name + " sits in seat " + seat)

def seats_left(total, taken):
    return total - taken

make_label("Priya", "B12")
make_label("Owen", "C04")
print(seats_left(80, 57))

Output:

Priya sits in seat B12
Owen sits in seat C04
23

Here, make_label and seats_left each have two parameters. The calls pass values in order, and each call can use different data while the code inside the sub program stays the same. The order matters: swapping Priya and B12 would put the seat into name and the name into seat, so the label would make no sense.

Arguments in a call go to parameters in order: Priya and B12 to name and seat, and 80 and 57 to total and taken. Swapping the order gives name B12 and seat Priya.

Practise this