Menu

Sub Programs

Arrays as parameters and return values

An array (a list in Python) can be passed to a function or procedure as a parameter, just like a single number or a piece of text. The sub program uses the parameter name to reach the whole array and work through its elements, so the same code can process any set of data you hand to it. Nothing needs to be copied by hand โ€” you pass the array's name, and the parameter inside the sub program refers to that array.

Working with an array of any length

Inside the sub program you usually do not know how many elements will arrive, because a different call may pass a longer or shorter array. Rather than writing a fixed number, call len() on the array parameter and use the result to control a loop. The loop then runs once per element, so one sub program copes with two elements or two hundred without any changes.

def showBadges(badges):
    # loop once for each element, whatever the length
    for index in range(len(badges)):
        print(str(index + 1) + ". " + badges[index])

swimBadges = ["Star", "Dolphin", "Gold"]
showBadges(swimBadges)
showBadges(["Bronze", "Silver"])

Output:

1. Star
2. Dolphin
3. Gold
1. Bronze
2. Silver

The call showBadges(swimBadges) passes a three-element array, so the loop runs three times; the second call passes a two-element array and the same loop runs twice. The parameter badges always refers to whichever array was passed, and len(badges) gives the right count each time.

Returning an array

Arrays are returned in exactly the same way as any other value: a function builds a result and sends it back with return. The calling code stores the returned array in a variable, and can then index it, loop over it, or pass it into another sub program. It is good practice for the function to build a new array rather than changing the one it was given, so the original data is still usable afterwards.

def lowStock(counts):
    # build a new array of counts that need restocking
    restock = []
    for index in range(len(counts)):
        if counts[index] < 5:
            restock.append(counts[index])
    return restock

shelf = [9, 2, 7, 4]
toOrder = lowStock(shelf)
print(toOrder)
print(shelf)

Output:

[2, 4]
[9, 2, 7, 4]

Here lowStock makes an empty list, appends each count that is below 5 and returns the finished list. toOrder therefore holds only the items that need restocking, and because shelf itself was never changed it can still be used later in the program.

Practise this