Functions

Definition

A function is a block of code which is executed when it is called from somewhere in the program. A function will return a value.

Functions are perfect for abstraction. They allow us to write blocks of code which can be reused in different ways and in different programs.

Note

Functions and procedures are almost the same thing, but functions return a value, whereas procedures do not.

Easy example

def add(a, b):
    answer = a + b
    return answer

total = add(5, 2)

print(total)
Show/Hide Output
7

Note

add(5, 2) is a function call. We can call the procedure as many times as we wish in the program. 5 and 2 are values which we pass to the two arguments a and b.

Note

A function needs to be defined earlier in the program than when it is called.

Syntax

#define the function
def functionName(arg1, arg2, ...):
    print('put instructions here')
    return value

#call the procedure
procedureName()

Examples

Example 1 - Function to return a value

def pi():           #define the function
    return 3.14     #return a value

pi = pi()
print(pi)
Show/Hide Output
3.14

Note

This isn’t the best value for pi, but shows how a function can return a value.

Example 2 - Using an argument with a function

def ageInDays(years):   #years is the argument (input) given to the function
    days = years * 365  #the 'days' variable is only available in this function
    return days         #return the days variable

ageYears = int(input('How old are you? '))

ageDays = ageInDays(ageYears)   #call the function and assign the result to the variable 'agedays'

print(ageDays)
Show/Hide Output
How old are you? 15
5475

Example 3 - Function to return a choice made in a menu

def getMenuChoice():
    print('Main Menu')
    print('1. Play game')
    print('2. View high scores')
    print('3. Quit')

    choice = input('Please enter your choice as a number: ')

    return choice


chosenItem = getMenuChoice()

print(chosenItem)
Show/Hide Output
Main Menu
1. Play game
2. View high scores
3. Quit
Please enter your choice as a number: 3
3

Note

This example has been kept simple. In reality, you would want to do some validation with the user input - for example, is the number between 1 and 3, and has the user entered a number. This validation could all be done in the function.

Example 4 - Function to add 1 to each item in a list

def addOne(theList):
    for i in range(len(theList)):
        theList[i] = theList[i] + 1
    return theList

listA = [3,6,9,18]
listB = [-10,83,72,3]

print(addOne(listA))
print(addOne(listB))
Show/Hide Output
[4, 7, 10, 19]
[-9, 84, 73, 4]

Example 5 - Find the average of a list

def average(theList):
    total = 0
    length = len(theList)

    for i in range(length):
        total = total + theList[i]

    average = total / length

    return average

listA = [3,6,9,18]
listB = [-10,83,72,3]

print(average(listA))
print(average(listB))
Show/Hide Output
9.0
37.0

Example 6 - Find how many times a letter appears in a 2D list

def letterOccurrences(theLetter, theList):

    total = 0

    for i in range(len(theList)):
        for j in range(len(theList[i])):
            if theList[i][j] == theLetter:
                total = total + 1

    return total


listA = [['a','b','c'],['d','e','f'],['g','h','i']]
listB = [['a','b','b'],['b','a','c'],['b','b','a']]

print(letterOccurrences('e', listA))
print(letterOccurrences('b', listB))
Show/Hide Output
1
5

Example 7 - Using a function to update a global variable

pi = 3.14

def showAreaOfCircle(radius):
    area = pi * radius * radius
    print('Area: ' + str(area))

def updatePi(newPi):
    return newPi

showAreaOfCircle(10)

pi = updatePi(3.141)

showAreaOfCircle(10)
Show/Hide Output
Area: 314.0
Area: 314.1

See also

See how to do this using a global variable in Example 5 - Using global variables. Be aware that, in general, using a function to update a global variable is better practice than updating the variable directly using the global keyword.

Key points

Note

Any variables which you make inside the function (definition) are only available to code inside the function. They are known as local variables.

Note

If you need to access a global variable (outside a function) then you must first use the word global followed by the variable name. For example, global listA. In general, using global variables inside a function is seen as bad practice. Instead you should be passing them to the function through an argument.

Note

Wherever possible you should try to use procedures or functions as they tend to make your code more readable.

Note

Procedures and functions are ways of abstracting your program. If you can think of parts of the program that are similar, then it is best to abstract them into their own procedure or function.

Note

Procedures and functions are both types of subroutines in programming. Both use the def keyword in Python.