12.07.2015 Views

Think Python - Denison University

Think Python - Denison University

Think Python - Denison University

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 6Fruitfulfunctions6.1 ReturnvaluesSome of the built-in functions we have used, such as the math functions, produce results. Callingthefunctiongeneratesavalue,whichweusuallyassigntoavariableoruseaspartofanexpression.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 returnvalue isNone.In this chapter, we are (finally) going to write fruitful functions. The first example is area, whichreturns thearea of acirclewiththe given radius:def area(radius):temp = math.pi * radius**2return tempWe have seen thereturn statement before, but in a fruitful function thereturn statement includesanexpression. Thisstatementmeans: “Returnimmediatelyfromthisfunctionandusethefollowingexpression as a return value.” The expression can be arbitrarily complicated, so we could havewrittenthisfunction more concisely:def area(radius):return math.pi * radius**2Onthe other hand, temporary variables liketempoften make debugging easier.Sometimes itisuseful tohave multiple returnstatements, one ineach branch of aconditional:def absolute_value(x):if x < 0:return -xelse:return x

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

Saved successfully!

Ooh no, something went wrong!