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.

54 Chapter 6. Fruitful functions1. Start with a working program and make small incremental changes. At any point, if there isan error,you should have agood idea where itis.2. Usetemporary variables tohold intermediate values soyou can displayand check them.3. Once the program is working, you might want to remove some of the scaffolding or consolidatemultiplestatementsintocompoundexpressions,butonlyifitdoesnotmaketheprogramdifficult toread.Exercise 6.2 Use incremental development to write a function called hypotenuse that returns thelength of the hypotenuse of a right triangle given the lengths of the two legs as arguments. Recordeach stageof thedevelopment process as you go.6.3 CompositionAs you should expect by now, you can call one function from within another. This ability is calledcomposition.As an example, we’ll write a function that takes two points, the center of the circle and a point ontheperimeter, and computes the area ofthe circle.Assume that the center point is stored in the variables xc and yc, and the perimeter point is in xpandyp. Thefirststepistofindtheradiusofthecircle,whichisthedistancebetweenthetwopoints.We justwroteafunction,distance,that does that:radius = distance(xc, yc, xp, yp)The next stepistofind thearea of acirclewiththat radius; wejust wrotethat, too:result = area(radius)Encapsulating thesesteps inafunction, weget:def circle_area(xc, yc, xp, yp):radius = distance(xc, yc, xp, yp)result = area(radius)return resultThe temporary variables radius and result are useful for development and debugging, but oncetheprogram isworking, we can make it moreconcise bycomposing the function calls:def circle_area(xc, yc, xp, yp):return area(distance(xc, yc, xp, yp))6.4 BooleanfunctionsFunctions can return booleans, which is often convenient for hiding complicated tests inside functions.For example:def is_divisible(x, y):if x % y == 0:return Trueelse:return False

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

Saved successfully!

Ooh no, something went wrong!