10.1 Functions That Compute Values

In Chapter 3, we introduced functions as a mechanism for supporting encapsulation. Functions allow us to write an algorithm that solves a specific sub-problem, gives that algorithm a name, and keeps the algorithm logically separate from the rest of a program. We provide inputs to functions by passing arguments when we make function calls.

In this chapter, we’re going to learn how to write functions that have output as well. In a computer program, function output always takes the form of data. A function with output typically calculates some kind of result or answer, giving back whenever the function is called. An example of such a function is Python’s max() function. max() takes numbers as inputs and gives us back the single largest number from among its inputs, like so:

The program above prints the value 6 to the console since 6 is the largest of the three values given as inputs to max().

We’ll come back to explain how to use functions with outputs shortly. But first, we’re going to see how to return output when we write our function definitions.