Some of the built-in functions we have used, such as the math functions, have produced results. Calling the function generates a new value, which we usually assign to a variable or use as part of an expression.
e = math.exp(1.0) height = radius * math.sin(angle)
In this chapter, we are going to write functions that return values, which we will call fruitful functions, for want of a better name. The first example is area, which returns the area of a circle with the given radius:
import math def area(radius): temp = math.pi * radius**2 return temp
def area(radius): return math.pi * radius**2
Sometimes it is useful to have multiple return statements, one in each branch of a conditional:
def absoluteValue(x):
if x < 0:
return -x
else:
return x
Code that appears after a return statement, or any other place the flow of execution can never reach, is called dead code.
In a fruitful function, it is a good idea to ensure that every possible path through the program hits a return statement. For example:
def absoluteValue(x):
if x < 0:
return -x
elif x > 0:
return x
>>> print absoluteValue(0) None
As an exercise, write a compare function that returns 1 if x > y, 0 if x == y, and -1 if x < y.