Upload
others
View
3
Download
0
Embed Size (px)
Citation preview
ControlFlow:LoopStatementsAlooprepeatedlyexecutesasuiteofsub-statements,calledtheloopbody.Pythonprovidestwokindsofloopstatements:afor-loopandawhile-loop.ThisexercisegivesyoupracticewithloopsandwiththePythonTurtlemodule.Part(a)[For-loop]:Afor-loophastheform:
for v in collection: suite
wherevisaloopvariable;collectionisasequenceorsetofitems,calledacollection;andsuiteisanindentedsequenceofstatements,calledtheloopbody.Toexecuteafor-loop,theconsoleassignsvsuccessivevaluesfromcollectionandexecutessuitefollowingeachassignment,asshownontheright.Eachexecutionoftheloopbodyiscalledaniterationoftheloop.Theflowdiagramtotherightshowshowtheconsoleexecutesaforloopofthisform.Considertheprogramandtheflowdiagramforitbelow.Discusswithyourpartnerhowtheflowdiagramwasproducedfromtheprogram.
Arethere(more)itemsin
collection?
v=thenextitemincollection
suite
YES
NO
Nextstatement(a+erthefor-loop)
Priorstatement(beforethefor-loop)
Observethatwreferstoavalueoftypestrwhencontrol(execution)reachesline4ofthisprogram.InPython,astrisacollectionofcharacters(orstr’soflength1).Soline4willassigneachcharacterfromwtothevariablec,inorder,andexecuteline5(theloopbody)onsuccessiveiterations.Assumethattheuserenters"ctl"attheprompt(i.e.,thattheusertouchesthec-key,thenthet-key,thenthel-key,andthentheenter/return-key).Withyourpartner,‘execute’theprogramonpaper:Oneofyoukeepstrackofthestatementthatwillbeexecutednext,whiletheotherkeepstrackofthecurrentvalueofeachvariable.Whatoutputwilltheprogramproduceforthisuserinput?AFTERyouhavecompletedtheabove,checkyourunderstandingbysteppingthroughthevisualizationundertheVisualization1linkintheArtifactsectionoftoday’swebsite.Part(b)[Iteratingoverarange]:Pythonprovidesmanyfunctionsthatreturncollectionsforaprogramtoiterateover.Oneofthemostusefulistherangefunction,whichreturnseitheracollectionofintegersor,iftherearenointegersintherange,anemptycollection.Thesimplestformoftherangefunctiontakesasingleargument:1
range(stop):returnstherangeofintegersthatbeginswith0andcountsupto,butdoesnotinclude,stop
Workingwithapartner,downloadtriangles.pyintothefolderyoucreatedforthisweekandopenthefile(useeitherFile => Openoritsshortcut,⌘O).Thisprogramusestheturtlemodule.IfyouperformedtheHourofCodeexerciserecommendedintheCSE231Welcomemessage,youalreadyknowaboutthismodule.Ifyoudidnot,refertothe‘TurtleCheatSheet”asneeded.Lines7—13defineafunctioncalledpick_color,whichiscalledinline18torandomlychangethepencolor.We’lllearnaboutfunctionslater.Fornow,justusepick_colorlikeyouwouldanyotherfunctionthattakesnoarguments.
1Theothertwoformsoftherangefunctiontakeeithertwoorthreearguments:• range(start, stop):returnstherangethatbeginswithstartandcounts
upto,butdoesnotinclude,stop • range(start, stop, step):returnstherangethatbeginswithstart,
counts(upordown)bystep,andgoesto,butdoesnotinclude,stop
Runtheprogram.ItshouldcreateaPythonTurtleGraphicswindowanddrawa(randomly)coloredtriangleinthewindow.Ifyoudon’tseethewindow,lookforitunderotherwindowsonyourdisplay.Intheconsole,presstheenter/return-key,asinstructed.Runtheprograminthismannerseveraltimes.Withapartner,discusshowtheprogramworks,referringtothecheatsheetasnecessary.Checkyourunderstandingbyansweringthefollowing:• Whatlinesofcodemakeupthebodyofthefor-loop?
• Howmanytimesdoestheshellexecutethebodyofthefor-loop?
• Onwhatiterationofthefor-loopdoestheturtledrawthetriangle’sbase?…its
leftside?…itsrightside?
• Whatpurposedoesthelastinputexpression(line22)serve?(Ifyouareuncertain,tryrunningtheprogramwiththatlinecommentedout.)
Modifytheprogramtoprompttheuserforalengthinpixels(apostiveint)andthen:(1) drawafilledequilateraltrianglewithside-lengthequaltotheuser-provided
lengthandwiththebasecenteredontheorigin,and(2) displaywhatsideisbeingdrawnintheconsolejustbeforedrawingeachside.
Forexample(here,theuserenteredthe‘200’afterthefirstprompt):
Part(c)[While-loop]:Awhile-loopismoreversatilethanafor-loop.2Theformofabasicwhile-loopis: while cond: suite wherecondisaloopcondition(Booleanexpression)andsuiteisaloopbody(indentedsequenceofstatements).Toexecuteawhileloop,theconsoleevaluatescondand,ifcondisTrue,itrepeatedlyexecutessuiteuntilcondbecomesFalse,whenitterminatestheloop.3Theflowdiagramtotherightdepictsthecontrolflow.
Acommoninputpatternistorepeatedlyrequesta“legal”input,untiltheuserentersone.Youcanimplementthispatternusingawhileloop,asshownbythepseudo-codetotheright.Modifyyourtrianglesprogramsothatitpromptstheuserforapositivelengththatisnomorethan600,repeatedly,untiltheuserentersalegallength.Itshouldthendrawthetriangleasinpart(b),withthebaseonthex-axisandcenteredonthey-axis.Also,itshouldprintanerrormessageiftheuserentersanillegalinteger.Forexample:
(Youwillfixtheproblemofthetrianglebeing“cutoff”inalaterpartofthisexercise.)
2Everyfor-loopcanbereplacedwithawhile-loop;butsomeproblems—e.g.,theinputprobleminthispart—cannotbesolvedusingafor-loop.3Forsimplicity,wedescribethetypicalcase.Ingeneral,theloopconditioncanhaveanytype;Pythontreatsaloopconditionthatisnon-zeroornon-emptyasTrue,andaloopconditionthatiszerooremptyasFalse.
is
cond == True?
suite
YES
NO
Nextstatement(a+erthewhile-loop)
Priorstatement(beforethewhie-loop)
Part(d)[Problemsolving,nestedloops]:Modifyyourprogramsothatitdrawsa“row”ofasmanytrianglesascanfit,side-by-side,withinthecoordinates(-300,0)to(300,0).Centertherowoftriangleswithrespecttothey-axis.Selectarandomcolorforeachtriangle.Usethelengthenteredbyauser.Inthefollowingexample,youalsoseesomeoutputproducedbymyprogram,whichIusedfordebuggingpurposes:
Beforewritinganycode,workoutseveralexamplesonpaperusingsomeeasyinputlengths,e.g.,150,175.Howcanyoucalculatethemaximumnumberoftrianglesthatwillfit?Knowingthenumberoftriangles,howcanyoucalculatewheretostartdrawingeachtriangleinitsturn?Part(e)[Extraproblemsolvingforexperts]:Modifyyourprogramsothatitdrawsasmanyrowsoftrianglesascanfit,stackedoneontopoftheother,withinasquare600pixelswideand600pixelstallandcenteredattheorigin.Hint:Youcanusesometrigonometrytocalculatetheheightofthetriangles(arow).Then,youcanuseessentiallythesamelogicasinpart(d)tocalculatehowmanyrowswillfitandwheretostartdrawingeachrow.
Part(f)[Forgluttons,someexampracticeproblems]:Tracetheexecutionofthefollowingprogramassumingtheuserentersa319attheprompt.Traceaslongasneededtofigureoutwhatitdisplaysforthisinput.
Whatwillitdisplayiftheuserenters5003012attheprompt?Tracetheexecutionofthefollowingprogramassumingtheuserentersa5attheprompt.Traceaslongasneededtofigureoutwhatitdisplaysforthisinput.