Chapter 6. Return Values
In previous chapters, we’ve used built-in functions—like abs and round—and functions in the math module—like sqrt and pow. When you call one of these functions, it returns a value you can assign to a variable or use as part of an expression.
The functions we have written so far are different. Some use the print function to display values, and some use turtle functions to draw figures. But they don’t return values we assign to variables or use in expressions.
In this chapter, we’ll see how to write functions that return values.
Some Functions Have Return Values
When you call a function like math.sqrt, the result is called a return value. If the function call appears at the end of a cell, Jupyter displays the return value immediately:
importmathmath.sqrt(42/math.pi)
3.656366395715726
If you assign the return value to a variable, it doesn’t get displayed:
radius=math.sqrt(42/math.pi)
But you can display it later:
radius
3.656366395715726
Or you can use the return value as part of an expression:
radius+math.sqrt(42/math.pi)
7.312732791431452
Here’s an example of a function that returns a value:
defcircle_area(radius):area=math.pi*radius**2returnarea
circle_area takes radius as a parameter and computes the area of a circle with that radius.
The last line is a return statement that returns the value of area.
If we call the function like this, Jupyter displays the return value:
circle_area(radius)
42.00000000000001
We ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access