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.

6.2. Incremental development 53>>> distance(1, 2, 4, 6)0.0I chose these values so that the horizontal distance is 3 and the vertical distance is 4; that way, theresultis5(thehypotenuseofa3-4-5triangle). Whentestingafunction,itisusefultoknowtherightanswer.At this point we have confirmed that the function is syntactically correct, and we can start addingcode to the body. A reasonable next step is to find the differences x 2 −x 1 and y 2 −y 1 . The nextversion storesthose values intemporary variables and printsthem.def distance(x1, y1, x2, y2):dx = x2 - x1dy = y2 - y1print 'dx is', dxprint 'dy is', dyreturn 0.0If the function is working, it should display 'dx is 3' and ’dy is 4’. If so, we know that thefunction is getting the right arguments and performing the first computation correctly. If not, thereareonly afew lines tocheck.Next we compute thesum of squares ofdxanddy:def distance(x1, y1, x2, y2):dx = x2 - x1dy = y2 - y1dsquared = dx**2 + dy**2print 'dsquared is: ', dsquaredreturn 0.0Again, you would run the program at this stage and check the output (which should be 25). Finally,you can usemath.sqrttocompute and returntheresult:def distance(x1, y1, x2, y2):dx = x2 - x1dy = y2 - y1dsquared = dx**2 + dy**2result = math.sqrt(dsquared)return resultIfthatworkscorrectly,youaredone. Otherwise,youmightwanttoprintthevalueofresultbeforethereturn statement.The final version of the function doesn’t display anything when it runs; it only returns a value.The print statements we wrote are useful for debugging, but once you get the function working,you should remove them. Code like that is called scaffolding because it is helpful for building theprogram but isnot part of thefinal product.When you start out, you should add only a line or two of code at a time. As you gain more experience,you might find yourself writing and debugging bigger chunks. Either way, incrementaldevelopment can save you a lotof debugging time.The key aspects of theprocess are:

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

Saved successfully!

Ooh no, something went wrong!