06.09.2021 Views

How to Think Like a Computer Scientist - Learning with Python, 2008a

How to Think Like a Computer Scientist - Learning with Python, 2008a

How to Think Like a Computer Scientist - Learning with Python, 2008a

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 5<br />

Fruitful functions<br />

5.1 Return values<br />

Some of the built-in functions we have used, such as the math functions, have<br />

produced results. Calling the function generates a new value, which we usually<br />

assign <strong>to</strong> a variable or use as part of an expression.<br />

e = math.exp(1.0)<br />

height = radius * math.sin(angle)<br />

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

In this chapter, we are going <strong>to</strong> write functions that return values, which we will<br />

call fruitful functions, for want of a better name. The first example is area,<br />

which returns the area of a circle <strong>with</strong> the given radius:<br />

import math<br />

def area(radius):<br />

temp = math.pi * radius**2<br />

return temp<br />

We have seen the return statement before, but in a fruitful function the return<br />

statement includes a return value. This statement means: “Return immediately<br />

from this function and use the following expression as a return value.” The expression<br />

provided can be arbitrarily complicated, so we could have written this<br />

function more concisely:<br />

def area(radius):<br />

return math.pi * radius**2

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!