5.3. Return values#
The majority of functions output (or return) an object or a tuple of multiple objects. To return something from a function we use the return
command.
def function(argument1, argument2, ...)
commands to be executed
return output
Important
The when the return
command is encountered the function terminates and any indented code following it will not be executed.
To demonstrate this enter the following code into your program.
# Return values
def double(x):
return 2 * x
print()
print(double(3))
print(double(5))
Run your program and you should see the following added to the console.
6
10
5.3.1. Multiple return values#
We can return multiple values from a function by listing them after the return
command.
def function(argument1, argument2, ...)
commands to be executed
return output1, output2, ...
To demonstrate this lets write a function calculates the area and circumference of a circle. Enter the following code into your program.
# Multiple return values
from numpy import pi
def circle(radius):
area = pi * radius ** 2
circumference = 2 * pi * radius
return area, circumference
area, circ = circle(8)
print()
print(f"Area : {area:8.4f}")
print(f"Circumference : {circ:8.4f}")
Run your program and you should see the following added to the console.
5.3.1 Multiple return values
----------------------------
Area : 201.0619
Circumference : 50.2655
5.3.2. Exercises#
Write a function called norm()
that calculates the norm (magnitude) of a vector of unknown length. Use your function to calculate the norm of the following vectors:
\((1, 2, 3)\)
\((4, 5, 6, 7)\)
Euclid’s algorithm for computing the greatest common divisor (GCD) of two numbers \(x\) and \(y\) is
Find the remainder \(r\) of \({x}\div{y}\)
Set \(x = y\) and \(y = r\)
Repeat steps 1 and 2 until \(y = 0\) then the GCD is \(x\)
For example, lets calculate the GCD of 45 and 210. We have \(x = 45\) and \(y = 210\) and stepping through the algorithm
\(45/210 = 0\) remainder 45 so \(x = 210\) and \(y = 45\)
\(210/45 = 4\) remainder 30 so \(x = 45\) and \(y = 30\)
\(45/30 = 1\) remainder 15 so \(x = 30\) and \(y = 15\)
\(30/15 = 2\) remainder 0 so \(x = 15\) and \(y = 0\)
\(y = 0\) so the GCD is 15
Write a function called gcd()
that returns the GCD of two numbers. Use your function to calculate the GCD of:
14 and 245
2414 and 54145
The following sequence converges to the square root of a positive number \(x\)
where \(x_0 = 0\) and \(x_1 = 1\). For example, lets use this to calculate \(\sqrt{9}\):
Define a function called sqrt()
that calculates numbers in this sequence until the difference two successive numbers is less that \(5 \times 10^{-5}\). Use your function to calculate
\(\sqrt{144}\)
\(\sqrt{12345}\)