Functions

<< Previous: Procedures Next: Practical challenges 7 >>

Functions

Functions are subroutines that return one or more values to the main program. If a subroutine changes the value of a variable used elsewhere in the program then it should be a function not a procedure. Functions can also take parameters. The return value or values can be the same values passed in or different ones.

Defining a function

We could make a function add_two_nums that returns the result of adding them instead of printing the sum.

Example 1

def add_two_nums(num1,num2):
    total = num1 + num2
    return total

Example 2

def add_name(names_list):
    name = input("Enter the name of the new team member: ")
    names_list.append(name)
    return names_list

function defining syntax rules:

Calling a function

Like a procedure, a function is called by its identifier followed by empty brackets or brackets containing any arguments passed in. Passing the wrong number of arguments will result in an error.
By far the most important thing to remember when calling a function is it must be given somewhere to store any return values. Our example functions above may be called an used as shown below.

first = int(input("Enter a number: ""))
second = int(input("Enter a number: "))
result = add_two_nums(first, second)
print(f"{first} + {second} = {result}")

This returns the result of adding two numbers to the variable total. It is possible to use the same name for a variable passed in as an argument and the parameter but I have avoided that so as to be clear that the parameter is the name defined in the subroutine as a parameter and it shows how and where that value will be used while the actual value passed is the argument.

team = ["Bob","Jim","Sam"]
team = add_name(team)

The code above accepts the team list from the main program to use in the subroutine and returns the updated list after it is run.

Syntax checker

Fix the code below so the subroutine takes two integer inputs and outputs whether the first is a multipe of the second e.g. if the user enters 18 and then 3 the output will be 'This is a multiple'.





def add_name(names): # def not sub
    new_name = input("Enter the name of a new person: ") # indentation fixed
    if new_name not in names: # indentation corrected and condition fixed
        names.append(new_name) # indentation fixed
    else: # indentation fixed
        print(f"{new_name} is already in the list") # indentation fixed
    return names # indentation fixed
team = ["Bob","Jim","Sam"]
team = add_name(team) # the new team must be returned

Knowledge check


Questions:
Correct:

Question text


<< Previous: Procedures Next: Practical challenges 7 >>

© All materials created by and copyright S.Goff