12.07.2015 Views

Think Python - Denison University

Think Python - Denison University

Think Python - Denison University

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.

36 Chapter 4. Case study: interface designFor example, polyline requires four arguments: t has to be a Turtle; n is the number of linesegments, so it has to be an integer; length should be a positive number; and angle has to be anumber, which isunderstood tobe indegrees.These requirements are called preconditions because they are supposed to be true before the functionstartsexecuting.Conversely,conditionsattheendofthefunctionarepostconditions. Postconditionsinclude the intended effect of the function (like drawing line segments) and any side effects(likemoving theTurtleor making other changes intheWorld).Preconditions are the responsibility of the caller. If the caller violates a (properly documented!)precondition and thefunction doesn’t workcorrectly, thebug isinthe caller, not thefunction.4.11 Glossaryinstance: A member of a set. The TurtleWorld in this chapter is a member of the set of Turtle-Worlds.loop: A part of aprogram that can execute repeatedly.encapsulation: The process oftransforming asequence ofstatements intoafunction definition.generalization: The process of replacing something unnecessarily specific (like a number) withsomething appropriately general (likeavariable or parameter).keyword argument: An argument that includes thename ofthe parameter as a“keyword.”interface: Adescriptionofhowtouseafunction,includingthenameanddescriptionsoftheargumentsand returnvalue.refactoring: Theprocessofmodifyingaworkingprogramtoimprovefunctioninterfacesandotherqualities ofthe code.development plan: Aprocess forwritingprograms.docstring: A stringthat appears inafunction definition todocument the function’s interface.precondition: A requirement that should be satisfiedby thecaller before a function starts.postcondition: A requirement that should besatisfied bythe function before itends.4.12 ExercisesExercise 4.1 Download thecode inthischapter fromthinkpython.com/code/polygon.py.1. Writeappropriate docstrings forpolygon,arcandcircle.2. Draw a stack diagram that shows the state of the program while executing circle(bob,radius). You can do the arithmeticby hand or addprintstatements tothecode.3. TheversionofarcinSection4.7isnotveryaccuratebecausethelinearapproximationofthecircle is always outside the true circle. As a result, the turtle ends up a few units away fromthe correct destination. My solution shows a way to reduce the effect of this error. Read thecode and see ifitmakes sensetoyou. Ifyou draw a diagram, you might seehow itworks.

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

Saved successfully!

Ooh no, something went wrong!