Chapter 6. Fruitful Functions
Return Values
Some of the built-in functions we have used, such as the math functions, produce results. Calling the function generates a value, which we usually assign to a variable or use as part of an expression.
e=math.exp(1.0)height=radius*math.sin(radians)
All of the functions we have written so far are void; they print
something or move turtles around, but their return value is None.
In this chapter, we are (finally) going to write fruitful
functions. The first example is area,
which returns the area of a circle with the given radius:
defarea(radius):temp=math.pi*radius**2returntemp
We have seen the return
statement before, but in a fruitful function the return statement includes an expression. This
statement means: “Return immediately from this function and use the
following expression as a return value.” The expression can be
arbitrarily complicated, so we could have written this function more
concisely:
defarea(radius):returnmath.pi*radius**2
On the other hand, temporary
variables like temp often
make debugging easier.
Sometimes it is useful to have multiple return statements, one in each branch of a conditional:
defabsolute_value(x):ifx<0:return-xelse:returnx
Since these return statements
are in an alternative conditional, only one will be executed.
As soon as a return statement executes, the function terminates
without executing any subsequent statements. Code that appears after a
return statement, or any other place ...
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