Common Loop Algorithms 9/21/16 42
Common Loop Algorithms
9/21/16 42
Common Loop Algorithms 1. SumandAverageValue
2. Coun4ngMatches
3. Promp4ngun4laMatchIsFound
4. MaximumandMinimum
5. ComparingAdjacentValues
43 9/21/16
Sum Example • SumofValues
• Ini4alizetotalto0• Usewhileloopwithsen4nel
total=0.0inputStr=input("Entervalue:")whileinputStr!="":value=float(inputStr)total=total+valueinputStr=input("Entervalue:")
44 9/21/16
Average Example total=0.0count=0inputStr=input("Entervalue:")whileinputStr!="":value=float(inputStr)total=total+valuecount=count+1inputStr=input("Entervalue:")ifcount>0:average=total/countelse:average=0.0
AverageofValues
• Firsttotalthevalues• Ini4alizecountto0
• Incrementperinput
• Checkforcount0
• Beforedivide!
45 9/21/16
Counting Matches (e.g., Negative Numbers)
negatives=0inputStr=input("Entervalue:")whileinputStr!="“:value=int(inputStr)ifvalue<0:negatives=negatives+1inputStr=input("Entervalue:")print("Therewere",negatives,"negativevalues.")
• Coun4ngMatches
• Ini4alizenega4vesto0• Useawhileloop• Addtonega4vespermatch
46 9/21/16
Prompt Until a Match is Found • Ini4alizebooleanflagtoFalse• Testsen4nelinwhileloop
• Getinput,andcomparetorange• Ifinputisinrange,changeflagtoTrue• Loopwillstopexecu4ng
valid=Falsewhilenotvalid:value=int(input("Pleaseenterapositivevalue<100:"))ifvalue>0andvalue<100:valid=Trueelse:print("Invalidinput.")
47
Thisisanexcellentwaytovalidateuseprovidedinputs
9/21/16
Maximum • Getfirstinputvalue
• Bydefini4on,thisisthelargestthatyouhaveseensofar
• Loopwhileyouhaveavalidnumber(non-sen4nel)• Getanotherinputvalue• Comparenewinputtolargest(orsmallest)• Updatelargestifnecessary
largest=int(input("Enteravalue:"))inputStr=input("Enteravalue:")whileinputStr!=””:value=int(inputStr)ifvalue>largest:largest=valueinputStr=input("Enteravalue:")
48 9/21/16
Minimum • Getfirstinputvalue
• Thisisthesmallestthatyouhaveseensofar!
• Loopwhileyouhaveavalidnumber(non-sen4nel)• Getanotherinputvalue• Comparenewinputtolargest(orsmallest)• Updatesmallestifnecessary
smallest=int(input("Enteravalue:"))inputStr=input("Enteravalue:")whileinputStr!="“:value=int(inputStr)ifvalue<smallest:smallest=valueinputStr=input("Enteravalue:")
49 9/21/16
Comparing Adjacent Values • Getfirstinputvalue• Usewhiletodetermineiftherearemoretocheck
• Copyinputtopreviousvariable• Getnextvalueintoinputvariable• Compareinputtoprevious,andoutputifsame
value=int(input("Enteravalue:"))inputStr=input("Enteravalue:")whileinputStr!="“:previous=valuevalue=int(inputStr)ifvalue==previous:print("Duplicateinput")inputStr=input("Enteravalue:")
50 9/21/16
Grades Example • Openthefile:
• Grades.py
• Lookcarefullyatthesourcecode.• Themaximumpossiblescoreisreadasuserinput
• Thereisalooptovalidatetheinput
• Thepassinggradeiscomputedas60%oftheavailablepoints
51 9/21/16
The for Loop
9/21/16 52
The for Loop • Usesofaforloop:
• Theforloopcanbeusedtoiterateoverthecontentsofanycontainer.
• Acontainerisanobject(Likeastring)thatcontainsorstoresacollec4onofelements
• Astringisacontainerthatstoresthecollec4onofcharactersinthestring
53 9/21/16
while loop -> for loop
stateName="Virginia"i=0whilei<len(stateName):letter=stateName[i]print(letter)i=i+1
whileversion
54 9/21/16
while loop -> for loop
stateName="Virginia"i=0whilei<len(stateName):letter=stateName[i]print(letter)i=i+1
whileversion
stateName="Virginia"forletterinstateName:print(letter)
forversion
55 9/21/16
while loop -> for loop
stateName="Virginia"i=0whilei<len(stateName):letter=stateName[i]print(letter)i=i+1
whileversion
stateName="Virginia"forletterinstateName:print(letter)
forversion
• Noteanimportantdifferencebetweenthewhileloopandtheforloop.• Inthewhileloop,theindexvariableiisassigned0,1,andsoon.• Intheforloop,theelementvariableisassignedstateName[0],stateName[1],andsoon.
56 9/21/16
The for Loop (2) • Usesofaforloop:
• Aforloopcanalsobeusedasacount-controlledloopthatiteratesoverarangeofintegervalues.
i=1whilei<10:print(i)i=i+1
foriinrange(1,10):print(i)
while version
for version
57 9/21/16
Syntax of a for Statement (Container) • Usingaforlooptoiterateoverthecontentsofacontainer,anelementata4me.
58 9/21/16
Syntax of a for Statement (Range) • Youcanuseaforloopasacount-controlledlooptoiterateoverarangeofintegervalues
• Weusetherangefunc4onforgenera4ngasequenceofintegersthatlessthantheargumentthatcanbeusedwiththeforloop
59 9/21/16
Planning a for Loop • Printthebalanceattheendofeachyearforanumberofyears
60 9/21/16
Good Examples of for Loops • Keeptheloopssimple!
61 9/21/16
Investment Example
62 9/21/16
Programming Tip • Findingthecorrectlowerandupperboundsforaloopcanbeconfusing.• Shouldyoustartat0orat1?• Shouldyouuse<=bor<basatermina4oncondi4on?
• Coun4ngiseasierforloopswithasymmetricbounds.• Thefollowingloopsareexecutedb-a4mes.
inti=awhilei<b:...i=i+1
foriinrange(a,b):...
63 9/21/16
Programming Tip • Theloopwithsymmetricbounds(“<=”,isexecutedb-a+14mes.
• That“+1”isthesourceofmanyprogrammingerrors.
i=awhilei<=b:...i=i+1
#Forthisversionoftheloopthe‘+1’isverynoticeable!foryearinrange(1,numYears+1):
64 9/21/16
Summary of the for Loop • forloopsareverypowerful• Theforloopcanbeusedtoiterateoverthecontentsofanycontainer,whichisanobjectthatcontainsorstoresacollec4onofelements• astringisacontainerthatstoresthecollec4onofcharactersinthestring.
• Aforloopcanalsobeusedasacount-controlledloopthatiteratesoverarangeofintegervalues.
65 9/21/16
Steps to Writing a Loop • Planning:
• Decidewhatworktodoinsidetheloop• Specifytheloopcondi4on• Determinelooptype• Setupvariablesbeforethefirstloop• Processresultswhentheloopisfinished• Tracetheloopwithtypicalexamples
• Coding:• ImplementtheloopinPython
66 9/21/16
A Special Form of the print Function
• Pythonprovidesaspecialformoftheprintfunc4onthatdoesnotstartanewlineajertheargumentsaredisplayed
• Thisisusedwhenwewanttoprintitemsonthesamelineusingmul4pleprintstatements
• Forexamplethetwostatements:
print(“00”,end=””)print(3+4)
• Producetheoutput:007
• Includingend=“”asthelastargumenttotheprintfunc4onprintsanemptystringajerthearguments,insteadonanewline
• Theoutputofthenextprintfunc4onstartsonthesameline
9/21/16 67
Nested Loops
9/21/16 68
Loops Inside of Loops • InChapterThreewelearnedhowtonestifstatementstoallowustomakecomplexdecisions• Rememberthattonesttheifstatementsweneedtoindentthecodeblock
• Complexproblemssome4mesrequireanestedloop,oneloopnestedinsideanotherloop• Thenestedloopwillbeindentedinsidethecodeblockofthefirstloop
• Agoodexampleofusingnestedloopsiswhenyouareprocessingcellsinatable• Theouterloopiteratesoveralloftherowsinthetable• Theinnerloopprocessesthecolumnsinthecurrentrow
9/21/16 69
Our Example Problem Statement • PrintaTableHeaderthatcontainsx1,x2,x3,andx4• PrintaTablewithfourcolumnsandtenrowsthatcontainthepowersofx1,x2,x3,andx4forx=1to10
9/21/16 70
Applying Nested Loops • Howwouldyouprintatablewithrowsandcolumns?
• Printtopline(header)• Useaforloop
• Printtablebody…• Howmanyrowsareinthetable?• Howmanycolumnsinthetable?
• Loopperrow• Looppercolumn
• Inourexamplethereare:• Fourcolumnsinthetable• Tenrowsinthetable
9/21/16 71
Pseudocode to Print the Table Printthetableheader
forxfrom1to10printanewtablerowprintanewline
• Howdoweprintatablerow?
Fornfrom1to4printxn
• Wehavetoplacethisloopinsidetheprecedingloop• Theinnerloopis“nested”insidetheouterloop
9/21/16 72
Pseudocode to Print the Table Printthetableheader:
forxfrom1to10fornfrom1to4printXn
printanewline
9/21/16 73
n !
x!
InnerLoop
Flowchart of a Nested Loop x=1
x<=10? n=1
n<=4? Printxn
n=n+1
Printnewline
x=x+1
True
False True
Done
False
9/21/16 74
Powertable.py
9/21/16 75
Bodyofouterloop,x=1!10
Bodyofinnerloop,n=1!4
The end=“” suppresses the new line, so the numbers are all printed on the same line
The Results
9/21/16 76
First Exercise • Opentheprogram:
• powertable.py
• Runtheprogramandreviewtheresults
• Makethefollowingchanges:• ChangethevalueofNMAXto6andruntheprogram• Whatchangesinthetable?• ChangethevalueofNMAXbackto4• ChangethevalueofXMAXto4• Whatchangesinthetable?
9/21/16 77
Nested Loop Examples
9/21/16 78
Hand Tracing the Loop
• iwillhavethevalues:• 0,1,2,3–Sowewillhavefourlinesofstars
• jwillhavethevalues• 0-Sowewillhaveonestar• 0,1-Sowewillhavetwostars• 0,1,2-Sowewillhavethreestars• 0,1,2,3-Sowewillhavefourstars
9/21/16 79
Nested Loop Examples (2)
9/21/16 80
Second Problem Statement • Printthefollowingpapernofbrackets:[][][][][][][][][][][][]
• Thepapernconsistsof:• Threerows• Eachrowhasfourpairsofbrackets
• Whatdoweknow?• Weneedtwonestedloops
• Thefirstloop(theouterloop)willprinteachofthethreerows• Thesecondloop(theinnerloop)willprintthefourpairsofbrackets
9/21/16 81
Pseudocode Code, Results Fori=1to3Forj=1to4Print“[]”
Printanewline
9/21/16 82
Exam Averages Problem Statement • Itiscommontorepeatedlyreadandprocessmul4plegroupsofvalues:
• Writeaprogramthatcancomputetheaverageexamgradeformul4plestudents.
• Eachstudenthasthesamenumberofexamgrades• Prompttheuserforthenumberofexams• Whenyoufinishastudentprompttheusertoseeiftherearemorestudentstoprocess
• Whatdoweknow?
• Whatdoweneedtocompute?
• Whatisouralgorithm/approach?
9/21/16 83
Step One: Understand the Problem • Tocomputetheaveragegradeforastudent,wemustreadandtallyallofthegradesforthatstudent• Wecanusealooptodothis.(wehaveworkingcodetodothispor8on)
• Weneedtocomputegradesformul4plestudents• ThatimpliesasetofnestedLoops
• Theouterloopprocesseseachstudent• Theinnerloopprocessthestudent’sgrades
9/21/16 84
Step Two • Computethegradeforonestudent
• Setupthevariablesandloop
• Weknowhowmanygradestoprocess,sowecanuseacount-controlledloop
totalscore=0Foriinrange(1,numberofexams+1):ReadthenextexamscoreAddtheexamscoretothetotalscore
ComputetheexamaveragePrinttheexamaverage
9/21/16 85
Step Three • Repeattheprocessforeachstudent• Sincewedon’tknowhowmanystudentsthereare,wewilluseawhileloopwithasen4nelvalue• Forsimplicitywewilluse“Y”asthesen4nelvalue
9/21/16 86
Step Four: Translate to Python
9/21/16 87
Exam Averages Example • Openthefile:
• examaverages.py
• No4cethatthesecondloop(theforloop)isnestedinsidethewhileloop• InWingyoushouldseealine(theindentguide)connec4ngtheforlooponline17downtothestatementonline21• Thelineisshowingyouthestatementsthatareincludedintheforloop
• Ifyoudon’tseetheindentguide:• Clickontheedittab• Select“Preferences…”• UnderEditor,selectInden4on• Clickthe“ShowIndentGuides”box• ClicktheApplybupon• ClicktheOkayBupon
9/21/16 88
Turning the Indent Guides On
9/21/16 89
Application: Random Numbers and Simulations
9/21/16 90
Random Numbers/Simulations • Gamesojenuserandomnumberstomakethingsinteres4ng
• RollingDice• Spinningawheel• Pickacard
• Asimula4onusuallyinvolvesloopingthroughasequenceofevents• Days• Events
9/21/16 91
Generating Random Numbers • ThePythonlibraryhasarandomnumbergeneratorthatproducesnumbersthatappeartoberandom• Thenumbersarenotcompletelyrandom.Thenumbersaredrawnfromasequenceofnumbersthatdoesnotrepeatforalong4me
• random()returnsanumberthatis>=0and<1
9/21/16 92
Simulating Die Tosses • Goal:
• Togeneratearandomintegerinagivenrangeweusetherandint()func4on
• Randinthastwoparameters,therange(inclusive)ofnumbersgenerated
9/21/16 93