Python Programming: An Introduction to Computer Science

(Nora) #1
5.4.GRAPHINGFUTUREVALUE 69

Figure5.7:Bargraphshowinggrowthof$2,000at 10%interest

Print an introduction
Get value of principaland apr from user
Create a GraphWin
Draw scale labels on leftside of window
Draw bar at position0 with height corresponding to principal
For successive years1 through 10
Calculate principal= principal * (1 + apr)
Draw a bar for thisyear having a height corresponding to principal
Wait for user to pressEnter


Thepausecreatedbythelaststepis necessaryto keepthegraphicswindow displayedsothatwecaninterpret
theresults.Withoutsucha pause,theprogramwouldendandtheGraphWinwouldvanishwithit.
Whilethisdesigngivesusthebroadbrushstrokesforouralgorithm,therearesomeveryimportantdetails
thathave beenglossedover. We mustdecideexactlyhow bigthegraphicswindow willbeandhow wewill
positiontheobjectsthatappearinthiswindow. Forexample,whatdoesit meantodraw, say, a barforyear
five withheightcorrespondingto$3,221.02?
Let’s startwiththesizeoftheGraphWin. Recallthatthesizeofa windowisgivenintermsofthe
numberofpixelsineachdimension.Computerscreensarealsomeasuredintermsofpixels.Thenumberof
pixelsorresolution ofthescreenis determinedbythemonitorandgraphicscardinthecomputeryouuse.
Thelowestresolutionscreenyouarelikelyto encounterthesedaysis a so-calledstandard VGAscreenthatis
640 x 480pixels.Mostscreensareconsiderablylarger. Let’s make theGraphWinonequarterthesizeofa
640 x 480screen,or 320 x 240.Thatshouldallow alluserstoseethegraphicaloutputaswellasthetextual
outputfromourprogram.
Giventhisanalysis,wecanfleshouta bitofourdesign.Thethirdlineofthedesignshouldnow read:


Create a 320 x 240 GraphWintitled ‘‘Investment Growth Chart’’


Youmaybewonderinghow thiswilltranslateintoPythoncode.Youhave alreadyseenthattheGraphWin
constructorallowsanoptionalparametertospecifythetitleofthewindow. Youmayalsosupplywidthand
heightparameterstocontrolthesizeofthewindow. Thus,thecommandtocreatetheoutputwindow willbe:


win = GraphWin("Investment Growth Chart", 320, 240)


Next weturnto theproblemofprintinglabelsalongtheleftedgeofourwindow. To simplifytheproblem,
wewillassumethegraphis alwaysscaledtoa maximumof$10,000withthefive labels“0.0K”to“10.0K”
asshownintheexamplewindow. Thequestionis how shouldthelabelsbedrawn?We willneedsomeText

Free download pdf