Functions that Return ValuesΒΆ
Most functions require arguments, values that control how the function does its job.
In this example, the arguments to the abs
function are 5 and -5.
Some functions take more than one argument.
Note
Of course, we have already seen that raising a base to an exponent can be done with the ** operator.
Another built-in function that takes more than one argument is max
.
Functions that return values are sometimes called fruitful functions.
In many other languages, a chunk that doesn’t return a value is called a procedure or non-fruitful function.
Fruitful functions still allow the user to provide information (arguments). However there is now an additional piece of data that is returned from the function.
- How do we write our own fruitful function? Let’s start by creating a very simple mathematical function that we will call
square
. - The square function will take one number as a parameter and return the result of squaring that number.
- Here is the black-box diagram with the Python code following.
- The return statement is followed by an expression which is evaluated.
- Its result is returned to the caller as the “fruit” of calling this function.
As you step through the example in codelens notice that the return statement not only causes the function to return a value, but it also returns the flow of control back to the place in the program where the function call was made.
- All Python functions return the value
None
unless there is an explicit return statement with a value other thanNone.
- Consider the following common mistake made by beginning Python programmers.