next up previous contents index
Next: top Up: Fruitful functions Previous: Fruitful functions   Contents   Index

startsection section 1 0mm-3.5ex plus -1ex minus -.2ex0.7ex plus.2exReturn values

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)

But so far, none of the functions we have written has returned a value.

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

We have seen the return statement before, but in a fruitful function the return statement includes a return value. This statement means: ``Return immediately from this function and use the following expression as a return value.'' The expression provided can be arbitrarily complicated, so we could have written this function more concisely:


def area(radius):
  return math.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:


def absoluteValue(x):
  if x < 0:
    return -x
  else:
    return x

Since these return statements are in an alternative conditional, only one will be executed. As soon as one is executed, the function terminates without executing any subsequent statements.

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

This program is not correct because if x happens to be 0, neither condition is true, and the function ends without hitting a return statement. In this case, the return value is a special value called None:


>>> 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.


next up previous contents index
Next: top Up: Fruitful functions Previous: Fruitful functions   Contents   Index
root 2004-05-05