chapter 4: loops · 2016-09-16 · chapter goals • to implement while and for loops • to...
TRANSCRIPT
Chapter 4: Loops
Chapter Goals • Toimplementwhileandforloops
• Tohand-tracetheexecu6onofaprogram
• Tobecomefamiliarwithcommonloopalgorithms
• Tounderstandnestedloops
• Toimplementprogramsthatreadandprocessdatasets
• Touseacomputerforsimula6ons
Inthischapter,youwilllearnaboutloopstatementsinPython,aswellastechniquesforwri8ngprogramsthatsimulateac8vi8esinthereal
world.
2 9/16/16
Contents • Thewhileloop• ProblemSolving:Hand-Tracing
• Applica6on:ProcessingSen6nels• ProblemSolving:Storyboards
• CommonLoopAlgorithms
• Theforloop• Nestedloops
• ProcessingStrings• Applica6on:RandomNumbersandSimula6on
• Graphics:DigitalImageProcessing
• ProblemSolving:SolveaSimplerProblemFirst
3 9/16/16
The while Loop
9/16/16 4
The while Loop • Examplesofloopapplica6ons
• Calcula6ngcompoundinterest• Simula6ons,eventdrivenprograms• Drawing6les…
• Compoundinterestalgorithm(Chapter1)
Steps
5 9/16/16
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
Syntax: while Statement
7 9/16/16
Count-Controlled Loops • Awhileloopthatiscontrolledbyacountercounter=1#Initializethecounter
whilecounter<=10:#Checkthecounterprint(counter)counter=counter+1#Updatetheloopvariable
8 9/16/16
Event-Controlled Loops • Awhileloopthatiscontrolledbyaneventbalance=INITIAL_BALANCE#Initializetheloopvariable
whilebalance<=TARGET:#Checktheloopvariableyear–year+1balance=balance*2#Updatetheloopvariable
9 9/16/16
Execution of the Loop
10 9/16/16
Execution of the Loop (2)
11 9/16/16
Doubleinv.py
Declareandini6alizeavariableoutsideofthelooptocountyear
Incrementtheyearvariableeach6methrough
12 9/16/16
while Loop Examples
13 9/16/16
while Loop Examples (2)
14 9/16/16
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
Common Error: InfiniteLoops • Theloopbodywillexecuteun6lthetestcondi6onbecomesFalse.
• Whatifyouforgettoupdatethetestvariable?• balisthetestvariable(TARGETdoesn’tchange)• Youwillloopforever!(orun6lyoustoptheprogram)
whilebal<TARGET:year=year+1interest=bal*RATEbal=bal+interest
16 9/16/16
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
Hand Tracing Loops
9/16/16 18
Hand-Tracing Loops • Example:Calculatethesumofdigits(1+7+2+9)
• Makecolumnsforkeyvariables(n,total,digit)• Examinethecodeandnumberthesteps• Setvariablestostatebeforeloopbegins
19 9/16/16
Tracing Sum of Digits
• Startexecu6ngloopbodystatementschangingvariablevaluesonanewline
• Crossoutvaluesinpreviousline
20 9/16/16
Tracing Sum of Digits
• Con6nueexecu6ngloopstatementschangingvariables
• 1729/10leaves172(noremainder)
21 9/16/16
Tracing Sum of Digits • Testcondi6on.IfTrue,executeloopagain
• Variablenis172,Is172>0?,True!
• Makeanewlineforthesecond6methroughandupdatevariables
22 9/16/16
Tracing Sum of Digits • Third6methrough
• Variablenis17whichiss6llgreaterthan0
• Executeloopstatementsandupdatevariables
23 9/16/16
Tracing Sum of Digits • Fourthloopitera6on:
• Variablenis1atstartofloop.1>0?True• Executesloopandchangesvariablento0(1/10=0)
24 9/16/16
Tracing Sum of Digits • Becausenis0,theexpression(n>0)isFalse• Loopbodyisnotexecuted
• Jumpstonextstatementaaertheloopbody
• Finallyprintsthesum!
25 9/16/16
Summary of the while Loop • whileloopsareverycommon
• Ini6alizevariablesbeforeyoutest• Thecondi6onistestedBEFOREtheloopbody
• Thisiscalledpre-test• Thecondi6onoaenusesacountervariable
• Somethinginsidetheloopshouldchangeoneofthevariablesusedinthetest
• Watchoutforinfiniteloops!
26 9/16/16
Investment Example • Openthefile:
• Doubleinv.py
• Runtheprogramwithseveraltestcases• Theprogramwillpromptyouforarate• Enteramixofvalidandinvalidrates
27 9/16/16
Sentinel Values
9/16/16 28
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
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
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
Sentinel.py (2)
Prevent divide by 0
Calculate and output the average salary using the totaland count variables
32 9/16/16
Sentinel Example • Openthefile:
• Sen6nal.py
• No6cetheuseoftheIF()testinsidethewhileloop• TheIF()checkstomakesurewearenotprocessingthesen6nelvalue
33 9/16/16
Priming Read • Someprogrammersdon’tlikethe“trick”ofini6alizingtheinputvariablewithavalueotherthanasen6nel.
#Setsalarytoavaluetoensurethattheloop#executesatleastonce.salary=0.0whilesalary>=0:
salary=float(input("Enterasalaryor-1tofinish:"))whilesalary>=0:
34 9/16/16
• Analterna6veistochangethevariablewithareadbeforetheloop.
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
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
Storyboards
9/16/16 37
Storyboards • Oneusefulproblemsolvingtechniqueistheuseofstoryboardstomodeluserinterac6on.Itcanhelpanswer:• Whatinforma6ondoestheuserprovide,andinwhichorder?• Whatinforma6onwillyourprogramdisplay,andinwhichformat?• Whatshouldhappenwhenthereisanerror?• Whendoestheprogramquit?
• Astoryboardconsistsofannotatedsketchesforeachstepinanac8onsequence.
38 9/16/16
Storyboard Example • Goal:Conver6ngasequenceofvalues
• Willrequirealoopandsomevariables• Handleoneconversioneach6methroughtheloop
39 9/16/16
What Can Go Wrong? Unknownunittypes
• Whatistheusermisspellscen6metersandinches?• Whatotherconversionsareavailable?• Solu6on:
• Showalistoftheacceptableunittypes
40 9/16/16
What Else Can Go Wrong? • Howdoestheuserquittheprogram?
• Storyboardshelpyouplanaprogram• Knowingtheflowhelpsyoustructureyourcode
41 9/16/16