1.6 Functions

After the total and the average, next on my to-do list is to calculate the largest number of deaths.

An image with an angel in prayer statue in the foreground of a graveyard
Figure 5

This will be the maximum. It takes another single line of code to calculate it.

max(deathsInAngola, deathsInBrazil, deathsInPortugal)

6900

In this expression, max() is a function – the parenthesis are a reminder that the name max doesn’t refer to a variable. A function is a piece of code that calculates ( returns ) a value, given zero or more values (the function’s arguments ). In this case, max() has three arguments and returns the greatest of them. Actually, max() can calculate the maximum of two, three, four or more values.

max(deathsInBrazil, deathsInPortugal)

4400

The expressions above are function calls. I’m calling the max() function with three or two arguments, and the value of the expression is the value returned by the function. A function is called by writing its name, followed by the arguments, within parentheses and separated by commas. Function names follow the same rules as variable names.

As you might expect, Python also has a function to calculate the smallest (minimum) of two or more values.

min(deathsInAngola, deathsInBrazil, deathsInPortugal)

140

The value returned by a function call can be assigned to a variable. Here is an example, which calculates the range of deaths. The range of a set of values is the difference between the largest and the smallest of them.

largest = max(deathsInAngola, deathsInBrazil, deathsInPortugal)

smallest = min(deathsInAngola, deathsInBrazil, deathsInPortugal)

range = largest - smallest

range

6760

Exercise 3 Functions

Identify different types of error (some of you may have experienced those already…) in Exercise 3. You’ll need to use the Week 1 notebook to answer question three.

1. If the function name is misspelled as Min, what kind of error is it?

 

2. If a parenthesis or comma is forgotten, what kind of error is it?

 

3. Use Exercise 3 in the Week 1 exercise notebook to answer this question.

What is the range of deaths among the BRICS countries (Brazil, Russia, India, China, South Africa)?