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.

52 Chapter 6. Fruitful functionsSince thesereturnstatements areinan alternative conditional, only one willbe executed.As soon as a return statement executes, the function terminates without executing any subsequentstatements. Codethatappearsafterareturnstatement,oranyotherplacetheflowofexecutioncannever reach, iscalled dead code.In a fruitful function, it is a good idea to ensure that every possible path through the program hits areturnstatement. For example:def absolute_value(x):if x < 0:return -xif x > 0:return xThis function is incorrect because if x happens to be 0, neither condition is true, and the functionends without hitting a return statement. If the flow of execution gets to the end of a function, thereturnvalue isNone,which isnot the absolute value of0.>>> print absolute_value(0)NoneBy theway, <strong>Python</strong> provides abuilt-infunction calledabsthat computes absolute values.Exercise 6.1 Writeacomparefunction that returns1ifx > y,0ifx == y,and-1ifx < y.6.2 IncrementaldevelopmentAs you writelarger functions, you might find yourself spending moretimedebugging.To deal with increasingly complex programs, you might want to try a process called incrementaldevelopment. The goal of incremental development is to avoid long debugging sessions by addingand testingonly asmall amount of code at atime.As an example, suppose you want to find the distance between two points, given by the coordinates(x 1 ,y 1 )and (x 2 ,y 2 ). Bythe Pythagorean theorem, thedistance is:√distance= (x 2 −x 1 ) 2 +(y 2 −y 1 ) 2The first step is to consider what a distance function should look like in <strong>Python</strong>. In other words,what aretheinputs (parameters) and what istheoutput (returnvalue)?Inthiscase,theinputsaretwopoints,whichyoucanrepresentusingfournumbers. Thereturnvalueisthedistance, which isafloating-point value.Already you can writean outline ofthe function:def distance(x1, y1, x2, y2):return 0.0Obviously, this version doesn’t compute distances; it always returns zero. But it is syntacticallycorrect, and itruns,which means that you can testitbefore you make itmore complicated.To testthe new function, call itwithsample arguments:

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

Saved successfully!

Ooh no, something went wrong!