Python Programming: An Introduction to Computer Science

(Nora) #1
68 CHAPTER5. OBJECTSANDGRAPHICS

leftEye.setOutline(’red’)
rightEye = Circle(Point(100,50), 5)
rightEye.setFill(’yellow’)
rightEye.setOutline(’red’)


Thiswillcertainlywork,butit’s cumbersome.We hadtowriteduplicatedcodeforthetwo eyes.That’s easy
todousinga “cutandpaste”approach,but it’s notveryelegant.If wedecidetochangetheappearanceofthe
eyes,wewillhave tobesuretomake thechangesintwo places.
Thegraphicslibraryprovidesa bettersolution;allgraphicalobjectssupportaclonemethodthat
makesa copy oftheobject.Usingclone, wecanrescuetheoriginalapproach.


Correct way to createtwo circles, using clone.


leftEye = Circle(Point(80,50), 5)
leftEye.setFill(’yellow’)
leftEye.setOutline(’red’)
rightEye = leftEye.clone()# rightEye is an exact copy of the left
rightEye.move(20,0)


Strategicuseofcloningcanmake somegraphicstasksmucheasier.


5.4 GraphingFutureValue


Nowthatyouhave someideaofhowtouseobjectsfromthegraphicsmodule,we’rereadytotrysome
realgraphicsprogramming.Oneofthemostimportantusesofgraphicsis providinga visualrepresentation
ofdata.They saya pictureis wortha thousandwords;it is almostcertainlybetterthana thousandnumbers.
Few programsthatmanipulatenumericdatacouldn’t beimprovedwitha bitofgraphicaloutput.Remember
theprograminChapter2 thatcomputedthefuturevalueofa tenyearinvestment? Let’s tryourhandat
creatinga graphicalsummary.
Programmingwithgraphicsrequirescarefulplanning.You’ll probablywantpencilandpaperhandyto
drawsomediagramsandscratchoutcalculationsaswegoalong.Asusual,webeginbyconsideringthe
specificationofexactlywhattheprogramwilldo.
Theoriginalprogramfutval.pyhadtwo inputs,theamountofmoney tobeinvestedandtheannual-
izedrateofinterest.Usingtheseinputs,theprogramcalculatedthechangeinprincipalyearbyyearforten
yearsusingtheformulaprincipal principal


1  apr. It thenprintedoutthefinalvalueoftheprincipal.In
thegraphicalversion,theoutputwillbea ten-yearbargraphwheretheheightofsuccessive barsrepresents
thevalueoftheprincipalinsuccessive years.
Let’s usea concreteexampleforillustration.Supposeweinvest$2000at 10%interest.Thistableshows
thegrowthoftheinvestmentovera ten-yearperiod:


Years Value
0 $2,000.00
1 $2,200.00
2 $2,420.00
3 $2,662.00
4 $2,928.20
5 $3,221.02
6 $3,542.12
7 $3,897.43
8 $4,287.18
9 $4,715.90
10 $5,187.49

Ourprogramwilldisplaythisinformationina bargraph.Figure5.7showsthedataingraphicalform.The
graphactuallycontainselevenbars.Thefirstbarshowstheoriginalvalueoftheprincipal.Forreference,
let’s numberthesebarsaccordingthethenumberofyearsofinterestaccrued,0–10.
Hereis a roughdesignfortheprogram.

Free download pdf