Python 7b - Functions

What is a Function?

A function is a subroutine that takes one or more values from the main program and returns a value back.


For example, transferring over a sphere’s radius from the main program for the function to calculate a surface area and then return that value back to the main program.


The two key differences between procedures and functions are:

  1. A function uses parameters to transfer data from the main program into the function.

  2. A functions returns a value back to the main program.

Writing Functions

When we call a subroutine we need to include the data to transfer to the subroutine as a parameter in brackets.


In the procedure examples on the last page there were no parameters so the brackets were left blank.


But let’s imagine the sphere example from the introduction above; in the main program we want to input the radius of the shape and then call the function to work out the surface area.


When we call the function we need to define the radius as a parameter within the brackets:

Now that we have sent the radius value over the subroutine we need to collect that value in the subroutine’s defined parameters.


When defining a procedure we left the parameters blank but now we have to state what we are transferring over, it makes sense to call it the same as the original value but you could change the name if you wished.

Remember the subroutine must be at the top of the program.

Defining a function could look like this:

Within a function you need to return a value back to the main program.


Here we want to calculate the surface area of a sphere based on the radius value that we read in from the main program.


To send a value back to the main program you must write return followed by the variable you wish to return. For example:

One last thing, if we want to print the returned value then we need to put the call subroutine line within a print command like so:

Looking good. But there are two ways that we could improve this specific program.


Firstly instead of using the int command before the input we could use float instead – float allows decimal numbers to be inputted which is more appropriate for this program. Also, the output line is not very helpful so we can insert a string to the print line and a comma to make it more useful:

The great thing about subroutines is that we can re-use the same code in a program for different jobs. For example the program below uses parameters for moving through a checkpoint system:

Practice Task

Create a program similar to the sphere example above, this time to work out the volume of a cylinder.

In the main program ask the user to enter the cylinder's radius and then its height.

The actual calculation should be done in a function and returned to the main program.

The calculation for a cylinder's volume is:

pi x (radius x radius) x height

Example solution:

© CSNewbs 2019