6
Control Flow: Loop Statements A loop repeatedly executes a suite of sub-statements, called the loop body. Python provides two kinds of loop statements: a for-loop and a while-loop. This exercise gives you practice with loops and with the Python Turtle module. Part (a) [For-loop]: A for-loop has the form: for v in collection: suite where v is a loop variable; collection is a sequence or set of items, called a collection; and suite is an indented sequence of statements, called the loop body. To execute a for-loop, the console assigns v successive values from collection and executes suite following each assignment, as shown on the right. Each execution of the loop body is called an iteration of the loop. The flow diagram to the right shows how the console executes a for loop of this form. Consider the program and the flow diagram for it below. Discuss with your partner how the flow diagram was produced from the program. Are there (more) items in collection? v = the next item in collection suite YES NO Next statement (a+er the for-loop) Prior statement (before the for-loop)

Control Flow: Loop Statementsldillon/cse-ctl/Fall2018/Meeting... · Control Flow: Loop Statements A loop repeatedly executes a suite of sub-statements, called the loop body.Python

  • Upload
    others

  • View
    3

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Control Flow: Loop Statementsldillon/cse-ctl/Fall2018/Meeting... · Control Flow: Loop Statements A loop repeatedly executes a suite of sub-statements, called the loop body.Python

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)

Page 2: Control Flow: Loop Statementsldillon/cse-ctl/Fall2018/Meeting... · Control Flow: Loop Statements A loop repeatedly executes a suite of sub-statements, called the loop body.Python

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

Page 3: Control Flow: Loop Statementsldillon/cse-ctl/Fall2018/Meeting... · Control Flow: Loop Statements A loop repeatedly executes a suite of sub-statements, called the loop body.Python

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):

Page 4: Control Flow: Loop Statementsldillon/cse-ctl/Fall2018/Meeting... · Control Flow: Loop Statements A loop repeatedly executes a suite of sub-statements, called the loop body.Python

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)

Page 5: Control Flow: Loop Statementsldillon/cse-ctl/Fall2018/Meeting... · Control Flow: Loop Statements A loop repeatedly executes a suite of sub-statements, called the loop body.Python

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.

Page 6: Control Flow: Loop Statementsldillon/cse-ctl/Fall2018/Meeting... · Control Flow: Loop Statements A loop repeatedly executes a suite of sub-statements, called the loop body.Python

Part(f)[Forgluttons,someexampracticeproblems]:Tracetheexecutionofthefollowingprogramassumingtheuserentersa319attheprompt.Traceaslongasneededtofigureoutwhatitdisplaysforthisinput.

Whatwillitdisplayiftheuserenters5003012attheprompt?Tracetheexecutionofthefollowingprogramassumingtheuserentersa5attheprompt.Traceaslongasneededtofigureoutwhatitdisplaysforthisinput.