chapter 4: loops · 2016-09-16 · chapter goals • to implement while and for loops • to...
TRANSCRIPT
![Page 1: Chapter 4: Loops · 2016-09-16 · Chapter Goals • To implement while and for loops • To hand-trace the execu6on of a program • To become familiar with common loop algorithms](https://reader033.vdocuments.mx/reader033/viewer/2022042613/5fb1680b4467451a9e4b90db/html5/thumbnails/1.jpg)
Chapter 4: Loops
![Page 2: Chapter 4: Loops · 2016-09-16 · Chapter Goals • To implement while and for loops • To hand-trace the execu6on of a program • To become familiar with common loop algorithms](https://reader033.vdocuments.mx/reader033/viewer/2022042613/5fb1680b4467451a9e4b90db/html5/thumbnails/2.jpg)
Chapter Goals • Toimplementwhileandforloops
• Tohand-tracetheexecu6onofaprogram
• Tobecomefamiliarwithcommonloopalgorithms
• Tounderstandnestedloops
• Toimplementprogramsthatreadandprocessdatasets
• Touseacomputerforsimula6ons
Inthischapter,youwilllearnaboutloopstatementsinPython,aswellastechniquesforwri8ngprogramsthatsimulateac8vi8esinthereal
world.
2 9/16/16
![Page 3: Chapter 4: Loops · 2016-09-16 · Chapter Goals • To implement while and for loops • To hand-trace the execu6on of a program • To become familiar with common loop algorithms](https://reader033.vdocuments.mx/reader033/viewer/2022042613/5fb1680b4467451a9e4b90db/html5/thumbnails/3.jpg)
Contents • Thewhileloop• ProblemSolving:Hand-Tracing
• Applica6on:ProcessingSen6nels• ProblemSolving:Storyboards
• CommonLoopAlgorithms
• Theforloop• Nestedloops
• ProcessingStrings• Applica6on:RandomNumbersandSimula6on
• Graphics:DigitalImageProcessing
• ProblemSolving:SolveaSimplerProblemFirst
3 9/16/16
![Page 4: Chapter 4: Loops · 2016-09-16 · Chapter Goals • To implement while and for loops • To hand-trace the execu6on of a program • To become familiar with common loop algorithms](https://reader033.vdocuments.mx/reader033/viewer/2022042613/5fb1680b4467451a9e4b90db/html5/thumbnails/4.jpg)
The while Loop
9/16/16 4
![Page 5: Chapter 4: Loops · 2016-09-16 · Chapter Goals • To implement while and for loops • To hand-trace the execu6on of a program • To become familiar with common loop algorithms](https://reader033.vdocuments.mx/reader033/viewer/2022042613/5fb1680b4467451a9e4b90db/html5/thumbnails/5.jpg)
The while Loop • Examplesofloopapplica6ons
• Calcula6ngcompoundinterest• Simula6ons,eventdrivenprograms• Drawing6les…
• Compoundinterestalgorithm(Chapter1)
Steps
5 9/16/16
![Page 6: Chapter 4: Loops · 2016-09-16 · Chapter Goals • To implement while and for loops • To hand-trace the execu6on of a program • To become familiar with common loop algorithms](https://reader033.vdocuments.mx/reader033/viewer/2022042613/5fb1680b4467451a9e4b90db/html5/thumbnails/6.jpg)
Planning the while Loop balance=10.0
target=100.0
year=0
rate=0.025
whilebalance<TARGET:
year=year+1
interest=balance*RATE/100
balance=balance+interest
Aloopexecutesinstruc8onsrepeatedlywhileacondi8onisTrue.
6 9/16/16
![Page 7: Chapter 4: Loops · 2016-09-16 · Chapter Goals • To implement while and for loops • To hand-trace the execu6on of a program • To become familiar with common loop algorithms](https://reader033.vdocuments.mx/reader033/viewer/2022042613/5fb1680b4467451a9e4b90db/html5/thumbnails/7.jpg)
Syntax: while Statement
7 9/16/16
![Page 8: Chapter 4: Loops · 2016-09-16 · Chapter Goals • To implement while and for loops • To hand-trace the execu6on of a program • To become familiar with common loop algorithms](https://reader033.vdocuments.mx/reader033/viewer/2022042613/5fb1680b4467451a9e4b90db/html5/thumbnails/8.jpg)
Count-Controlled Loops • Awhileloopthatiscontrolledbyacountercounter=1#Initializethecounter
whilecounter<=10:#Checkthecounterprint(counter)counter=counter+1#Updatetheloopvariable
8 9/16/16
![Page 9: Chapter 4: Loops · 2016-09-16 · Chapter Goals • To implement while and for loops • To hand-trace the execu6on of a program • To become familiar with common loop algorithms](https://reader033.vdocuments.mx/reader033/viewer/2022042613/5fb1680b4467451a9e4b90db/html5/thumbnails/9.jpg)
Event-Controlled Loops • Awhileloopthatiscontrolledbyaneventbalance=INITIAL_BALANCE#Initializetheloopvariable
whilebalance<=TARGET:#Checktheloopvariableyear–year+1balance=balance*2#Updatetheloopvariable
9 9/16/16
![Page 10: Chapter 4: Loops · 2016-09-16 · Chapter Goals • To implement while and for loops • To hand-trace the execu6on of a program • To become familiar with common loop algorithms](https://reader033.vdocuments.mx/reader033/viewer/2022042613/5fb1680b4467451a9e4b90db/html5/thumbnails/10.jpg)
Execution of the Loop
10 9/16/16
![Page 11: Chapter 4: Loops · 2016-09-16 · Chapter Goals • To implement while and for loops • To hand-trace the execu6on of a program • To become familiar with common loop algorithms](https://reader033.vdocuments.mx/reader033/viewer/2022042613/5fb1680b4467451a9e4b90db/html5/thumbnails/11.jpg)
Execution of the Loop (2)
11 9/16/16
![Page 12: Chapter 4: Loops · 2016-09-16 · Chapter Goals • To implement while and for loops • To hand-trace the execu6on of a program • To become familiar with common loop algorithms](https://reader033.vdocuments.mx/reader033/viewer/2022042613/5fb1680b4467451a9e4b90db/html5/thumbnails/12.jpg)
Doubleinv.py
Declareandini6alizeavariableoutsideofthelooptocountyear
Incrementtheyearvariableeach6methrough
12 9/16/16
![Page 13: Chapter 4: Loops · 2016-09-16 · Chapter Goals • To implement while and for loops • To hand-trace the execu6on of a program • To become familiar with common loop algorithms](https://reader033.vdocuments.mx/reader033/viewer/2022042613/5fb1680b4467451a9e4b90db/html5/thumbnails/13.jpg)
while Loop Examples
13 9/16/16
![Page 14: Chapter 4: Loops · 2016-09-16 · Chapter Goals • To implement while and for loops • To hand-trace the execu6on of a program • To become familiar with common loop algorithms](https://reader033.vdocuments.mx/reader033/viewer/2022042613/5fb1680b4467451a9e4b90db/html5/thumbnails/14.jpg)
while Loop Examples (2)
14 9/16/16
![Page 15: Chapter 4: Loops · 2016-09-16 · Chapter Goals • To implement while and for loops • To hand-trace the execu6on of a program • To become familiar with common loop algorithms](https://reader033.vdocuments.mx/reader033/viewer/2022042613/5fb1680b4467451a9e4b90db/html5/thumbnails/15.jpg)
Common Error: Incorrect Test Condition
• Theloopbodywillonlyexecuteifthetestcondi6onisTrue.• Ifbalisini6alizedaslessthantheTARGETandshouldgrowun6litreachesTARGET• Whichversionwillexecutetheloopbody?
whilebal<TARGET:year=year+1interest=bal*RATEbal=bal+interest
whilebal>=TARGET:year=year+1interest=bal*RATEbal=bal+interest
15 9/16/16
![Page 16: Chapter 4: Loops · 2016-09-16 · Chapter Goals • To implement while and for loops • To hand-trace the execu6on of a program • To become familiar with common loop algorithms](https://reader033.vdocuments.mx/reader033/viewer/2022042613/5fb1680b4467451a9e4b90db/html5/thumbnails/16.jpg)
Common Error: InfiniteLoops • Theloopbodywillexecuteun6lthetestcondi6onbecomesFalse.
• Whatifyouforgettoupdatethetestvariable?• balisthetestvariable(TARGETdoesn’tchange)• Youwillloopforever!(orun6lyoustoptheprogram)
whilebal<TARGET:year=year+1interest=bal*RATEbal=bal+interest
16 9/16/16
![Page 17: Chapter 4: Loops · 2016-09-16 · Chapter Goals • To implement while and for loops • To hand-trace the execu6on of a program • To become familiar with common loop algorithms](https://reader033.vdocuments.mx/reader033/viewer/2022042613/5fb1680b4467451a9e4b90db/html5/thumbnails/17.jpg)
Common Error: Off-by-OneErrors • A‘counter’variableisoaenusedinthetestcondi6on• Yourcountercanstartat0or1,butprogrammersoaenstartacounterat0
• IfIwanttopaintall5fingersononehand,whenIamdone?• Ifyoustartat0,use“<“ Ifyoustartat1,use“<=“• 0,1,2,3,4 1,2,3,4,5
finger=0FINGERS=5whilefinger<FINGERS:#paintfingerfinger=finger+1
finger=1FINGERS=5whilefinger<=FINGERS:#paintfingerfinger=finger+1
17 9/16/16
![Page 18: Chapter 4: Loops · 2016-09-16 · Chapter Goals • To implement while and for loops • To hand-trace the execu6on of a program • To become familiar with common loop algorithms](https://reader033.vdocuments.mx/reader033/viewer/2022042613/5fb1680b4467451a9e4b90db/html5/thumbnails/18.jpg)
Hand Tracing Loops
9/16/16 18
![Page 19: Chapter 4: Loops · 2016-09-16 · Chapter Goals • To implement while and for loops • To hand-trace the execu6on of a program • To become familiar with common loop algorithms](https://reader033.vdocuments.mx/reader033/viewer/2022042613/5fb1680b4467451a9e4b90db/html5/thumbnails/19.jpg)
Hand-Tracing Loops • Example:Calculatethesumofdigits(1+7+2+9)
• Makecolumnsforkeyvariables(n,total,digit)• Examinethecodeandnumberthesteps• Setvariablestostatebeforeloopbegins
19 9/16/16
![Page 20: Chapter 4: Loops · 2016-09-16 · Chapter Goals • To implement while and for loops • To hand-trace the execu6on of a program • To become familiar with common loop algorithms](https://reader033.vdocuments.mx/reader033/viewer/2022042613/5fb1680b4467451a9e4b90db/html5/thumbnails/20.jpg)
Tracing Sum of Digits
• Startexecu6ngloopbodystatementschangingvariablevaluesonanewline
• Crossoutvaluesinpreviousline
20 9/16/16
![Page 21: Chapter 4: Loops · 2016-09-16 · Chapter Goals • To implement while and for loops • To hand-trace the execu6on of a program • To become familiar with common loop algorithms](https://reader033.vdocuments.mx/reader033/viewer/2022042613/5fb1680b4467451a9e4b90db/html5/thumbnails/21.jpg)
Tracing Sum of Digits
• Con6nueexecu6ngloopstatementschangingvariables
• 1729/10leaves172(noremainder)
21 9/16/16
![Page 22: Chapter 4: Loops · 2016-09-16 · Chapter Goals • To implement while and for loops • To hand-trace the execu6on of a program • To become familiar with common loop algorithms](https://reader033.vdocuments.mx/reader033/viewer/2022042613/5fb1680b4467451a9e4b90db/html5/thumbnails/22.jpg)
Tracing Sum of Digits • Testcondi6on.IfTrue,executeloopagain
• Variablenis172,Is172>0?,True!
• Makeanewlineforthesecond6methroughandupdatevariables
22 9/16/16
![Page 23: Chapter 4: Loops · 2016-09-16 · Chapter Goals • To implement while and for loops • To hand-trace the execu6on of a program • To become familiar with common loop algorithms](https://reader033.vdocuments.mx/reader033/viewer/2022042613/5fb1680b4467451a9e4b90db/html5/thumbnails/23.jpg)
Tracing Sum of Digits • Third6methrough
• Variablenis17whichiss6llgreaterthan0
• Executeloopstatementsandupdatevariables
23 9/16/16
![Page 24: Chapter 4: Loops · 2016-09-16 · Chapter Goals • To implement while and for loops • To hand-trace the execu6on of a program • To become familiar with common loop algorithms](https://reader033.vdocuments.mx/reader033/viewer/2022042613/5fb1680b4467451a9e4b90db/html5/thumbnails/24.jpg)
Tracing Sum of Digits • Fourthloopitera6on:
• Variablenis1atstartofloop.1>0?True• Executesloopandchangesvariablento0(1/10=0)
24 9/16/16
![Page 25: Chapter 4: Loops · 2016-09-16 · Chapter Goals • To implement while and for loops • To hand-trace the execu6on of a program • To become familiar with common loop algorithms](https://reader033.vdocuments.mx/reader033/viewer/2022042613/5fb1680b4467451a9e4b90db/html5/thumbnails/25.jpg)
Tracing Sum of Digits • Becausenis0,theexpression(n>0)isFalse• Loopbodyisnotexecuted
• Jumpstonextstatementaaertheloopbody
• Finallyprintsthesum!
25 9/16/16
![Page 26: Chapter 4: Loops · 2016-09-16 · Chapter Goals • To implement while and for loops • To hand-trace the execu6on of a program • To become familiar with common loop algorithms](https://reader033.vdocuments.mx/reader033/viewer/2022042613/5fb1680b4467451a9e4b90db/html5/thumbnails/26.jpg)
Summary of the while Loop • whileloopsareverycommon
• Ini6alizevariablesbeforeyoutest• Thecondi6onistestedBEFOREtheloopbody
• Thisiscalledpre-test• Thecondi6onoaenusesacountervariable
• Somethinginsidetheloopshouldchangeoneofthevariablesusedinthetest
• Watchoutforinfiniteloops!
26 9/16/16
![Page 27: Chapter 4: Loops · 2016-09-16 · Chapter Goals • To implement while and for loops • To hand-trace the execu6on of a program • To become familiar with common loop algorithms](https://reader033.vdocuments.mx/reader033/viewer/2022042613/5fb1680b4467451a9e4b90db/html5/thumbnails/27.jpg)
Investment Example • Openthefile:
• Doubleinv.py
• Runtheprogramwithseveraltestcases• Theprogramwillpromptyouforarate• Enteramixofvalidandinvalidrates
27 9/16/16
![Page 28: Chapter 4: Loops · 2016-09-16 · Chapter Goals • To implement while and for loops • To hand-trace the execu6on of a program • To become familiar with common loop algorithms](https://reader033.vdocuments.mx/reader033/viewer/2022042613/5fb1680b4467451a9e4b90db/html5/thumbnails/28.jpg)
Sentinel Values
9/16/16 28
![Page 29: Chapter 4: Loops · 2016-09-16 · Chapter Goals • To implement while and for loops • To hand-trace the execu6on of a program • To become familiar with common loop algorithms](https://reader033.vdocuments.mx/reader033/viewer/2022042613/5fb1680b4467451a9e4b90db/html5/thumbnails/29.jpg)
Processing Sentinel Values • Sen6nelvaluesareoaenused:
• Whenyoudon’tknowhowmanyitemsareinalist,usea‘special’characterorvaluetosignalthe“last”item
• Fornumericinputofposi6venumbers,itiscommontousethevalue-1
Asen8nelvaluedenotestheendofadataset,butitisnotpartofthedata.
salary=0.0whilesalary>=0:salary=float(input())ifsalary>=0.0:total=total+salarycount=count+1
29 9/16/16
![Page 30: Chapter 4: Loops · 2016-09-16 · Chapter Goals • To implement while and for loops • To hand-trace the execu6on of a program • To become familiar with common loop algorithms](https://reader033.vdocuments.mx/reader033/viewer/2022042613/5fb1680b4467451a9e4b90db/html5/thumbnails/30.jpg)
Averaging a Set of Values • Declareandini6alizea‘total’variableto0• Declareandini6alizea‘count’variableto0
• Declareandini6alizea‘salary’variableto0• Promptuserwithinstruc6ons
• Loopun6lsen6nelvalueisentered• Saveenteredvaluetoinputvariable(‘salary’)• Ifsalaryisnot-1orless(sen6nelvalue)
• Addsalaryvariabletototalvariable• Add1tocountvariable
• Makesureyouhaveatleastoneentrybeforeyoudivide!• Dividetotalbycountandoutput.• Done!
30 9/16/16
![Page 31: Chapter 4: Loops · 2016-09-16 · Chapter Goals • To implement while and for loops • To hand-trace the execu6on of a program • To become familiar with common loop algorithms](https://reader033.vdocuments.mx/reader033/viewer/2022042613/5fb1680b4467451a9e4b90db/html5/thumbnails/31.jpg)
Sentinel.py (1)
Outside the while loop: declare and initialize variables to use
Input new salary and compare to sentinel
Update running total and count (to calculate the average later)
Since salary is initialized to 0, the while loop statements will execute at least once
31 9/16/16
![Page 32: Chapter 4: Loops · 2016-09-16 · Chapter Goals • To implement while and for loops • To hand-trace the execu6on of a program • To become familiar with common loop algorithms](https://reader033.vdocuments.mx/reader033/viewer/2022042613/5fb1680b4467451a9e4b90db/html5/thumbnails/32.jpg)
Sentinel.py (2)
Prevent divide by 0
Calculate and output the average salary using the totaland count variables
32 9/16/16
![Page 33: Chapter 4: Loops · 2016-09-16 · Chapter Goals • To implement while and for loops • To hand-trace the execu6on of a program • To become familiar with common loop algorithms](https://reader033.vdocuments.mx/reader033/viewer/2022042613/5fb1680b4467451a9e4b90db/html5/thumbnails/33.jpg)
Sentinel Example • Openthefile:
• Sen6nal.py
• No6cetheuseoftheIF()testinsidethewhileloop• TheIF()checkstomakesurewearenotprocessingthesen6nelvalue
33 9/16/16
![Page 34: Chapter 4: Loops · 2016-09-16 · Chapter Goals • To implement while and for loops • To hand-trace the execu6on of a program • To become familiar with common loop algorithms](https://reader033.vdocuments.mx/reader033/viewer/2022042613/5fb1680b4467451a9e4b90db/html5/thumbnails/34.jpg)
Priming Read • Someprogrammersdon’tlikethe“trick”ofini6alizingtheinputvariablewithavalueotherthanasen6nel.
#Setsalarytoavaluetoensurethattheloop#executesatleastonce.salary=0.0whilesalary>=0:
salary=float(input("Enterasalaryor-1tofinish:"))whilesalary>=0:
34 9/16/16
• Analterna6veistochangethevariablewithareadbeforetheloop.
![Page 35: Chapter 4: Loops · 2016-09-16 · Chapter Goals • To implement while and for loops • To hand-trace the execu6on of a program • To become familiar with common loop algorithms](https://reader033.vdocuments.mx/reader033/viewer/2022042613/5fb1680b4467451a9e4b90db/html5/thumbnails/35.jpg)
Modification Read • Theinputopera6onatthebonomoftheloopisusedtoobtainthenextinput.
#Primingreadsalary=float(input("Enterasalaryor-1tofinish:"))whilesalary>=0.0:total=total+salarycount=count+1#Modificationreadsalary=float(input("Enterasalaryor-1tofinish:"))
35 9/16/16
![Page 36: Chapter 4: Loops · 2016-09-16 · Chapter Goals • To implement while and for loops • To hand-trace the execu6on of a program • To become familiar with common loop algorithms](https://reader033.vdocuments.mx/reader033/viewer/2022042613/5fb1680b4467451a9e4b90db/html5/thumbnails/36.jpg)
Boolean Variables and Sentinels • Abooleanvariablecanbeusedtocontrolaloop
• Some6mescalleda‘flag’variable
done=Falsewhilenotdone:value=float(input("Enterasalaryor-1to
finish:"))ifvalue<0.0:done=Trueelse:#Processvalue
Initialize done so that the loop will execute
Set done ‘flag’ to True if sentinel value is found
36 9/16/16
![Page 37: Chapter 4: Loops · 2016-09-16 · Chapter Goals • To implement while and for loops • To hand-trace the execu6on of a program • To become familiar with common loop algorithms](https://reader033.vdocuments.mx/reader033/viewer/2022042613/5fb1680b4467451a9e4b90db/html5/thumbnails/37.jpg)
Storyboards
9/16/16 37
![Page 38: Chapter 4: Loops · 2016-09-16 · Chapter Goals • To implement while and for loops • To hand-trace the execu6on of a program • To become familiar with common loop algorithms](https://reader033.vdocuments.mx/reader033/viewer/2022042613/5fb1680b4467451a9e4b90db/html5/thumbnails/38.jpg)
Storyboards • Oneusefulproblemsolvingtechniqueistheuseofstoryboardstomodeluserinterac6on.Itcanhelpanswer:• Whatinforma6ondoestheuserprovide,andinwhichorder?• Whatinforma6onwillyourprogramdisplay,andinwhichformat?• Whatshouldhappenwhenthereisanerror?• Whendoestheprogramquit?
• Astoryboardconsistsofannotatedsketchesforeachstepinanac8onsequence.
38 9/16/16
![Page 39: Chapter 4: Loops · 2016-09-16 · Chapter Goals • To implement while and for loops • To hand-trace the execu6on of a program • To become familiar with common loop algorithms](https://reader033.vdocuments.mx/reader033/viewer/2022042613/5fb1680b4467451a9e4b90db/html5/thumbnails/39.jpg)
Storyboard Example • Goal:Conver6ngasequenceofvalues
• Willrequirealoopandsomevariables• Handleoneconversioneach6methroughtheloop
39 9/16/16
![Page 40: Chapter 4: Loops · 2016-09-16 · Chapter Goals • To implement while and for loops • To hand-trace the execu6on of a program • To become familiar with common loop algorithms](https://reader033.vdocuments.mx/reader033/viewer/2022042613/5fb1680b4467451a9e4b90db/html5/thumbnails/40.jpg)
What Can Go Wrong? Unknownunittypes
• Whatistheusermisspellscen6metersandinches?• Whatotherconversionsareavailable?• Solu6on:
• Showalistoftheacceptableunittypes
40 9/16/16
![Page 41: Chapter 4: Loops · 2016-09-16 · Chapter Goals • To implement while and for loops • To hand-trace the execu6on of a program • To become familiar with common loop algorithms](https://reader033.vdocuments.mx/reader033/viewer/2022042613/5fb1680b4467451a9e4b90db/html5/thumbnails/41.jpg)
What Else Can Go Wrong? • Howdoestheuserquittheprogram?
• Storyboardshelpyouplanaprogram• Knowingtheflowhelpsyoustructureyourcode
41 9/16/16