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.

4.6. Interface design 33This draws a 7-sided polygon with side length 70. If you have more than a few numeric arguments,itiseasytoforgetwhattheyare,orwhatordertheyshouldbein. Itislegal,andsometimeshelpful,toinclude thenames of theparameters intheargument list:polygon(bob, n=7, length=70)Thesearecalledkeywordargumentsbecausetheyincludetheparameternamesas“keywords”(nottobe confused with<strong>Python</strong> keywords likewhileanddef).This syntax makes the program more readable. It is also a reminder about how arguments andparameters work: when you call afunction, the arguments are assigned totheparameters.4.6 InterfacedesignThe next step is to write circle, which takes a radius, r, as a parameter. Here is a simple solutionthat usespolygontodraw a50-sided polygon:def circle(t, r):circumference = 2 * math.pi * rn = 50length = circumference / npolygon(t, n, length)The first line computes the circumference of a circle with radius r using the formula 2πr. Sincewe use math.pi, we have to import math. By convention, import statements are usually at thebeginning of thescript.n is the number of line segments in our approximation of a circle, so length is the length of eachsegment. Thus,polygondraws a50-sides polygon that approximates acircle withradiusr.One limitation of this solution is that n is a constant, which means that for very big circles, theline segments are too long, and for small circles, we waste time drawing very small segments. Onesolution would be to generalize the function by taking n as a parameter. This would give the user(whoever callscircle)morecontrol, but theinterface would be lessclean.Theinterfaceofafunctionisasummaryofhowitisused: whataretheparameters? Whatdoesthefunctiondo? Andwhatisthereturnvalue? Aninterfaceis“clean”ifitis“assimpleaspossible,butnot simpler. (Einstein)”In this example, r belongs in the interface because it specifies the circle to be drawn. n is lessappropriate because itpertains tothe details of how thecircleshould be rendered.Rather than clutter up the interface, it is better to choose an appropriate value of n depending oncircumference:def circle(t, r):circumference = 2 * math.pi * rn = int(circumference / 3) + 1length = circumference / npolygon(t, n, length)Now the number of segments is (approximately) circumference/3, so the length of each segmentis(approximately)3,whichissmallenoughthatthecircleslookgood,butbigenoughtobeefficient,and appropriate forany sizecircle.

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

Saved successfully!

Ooh no, something went wrong!