Python For GCSE
Functions

A function is a subroutine that returns information. If the square procedure from the previous page is written as a function, it would look like this,

def square2(n):
    sq = n * n
    return sq

x = square2(4)
print("4 squared is",x)
x = square2(10)
print("10 squared is",x)

The function does not contain any output statements. Its job is to make the result of the calculation available for the programmer to use as they see fit.

A function always includes at least one return statement. A true function will always return a value. Note the way that we call it is different. We need to make a variable equal to the value returned by the function.

It is generally more useful to write your subroutines as functions rather than procedures although there are times where this is not the case. In this example, the function allows us to do something a little different.

def square2(n):
    sq = n * n
    return sq

s = 0
for i in range(1,11):
    s = s + square2(i)
print(s)

In this program, we make multiple calls to the function, adding up the return values, outputting the result only when we are ready to do so.