chapter 4: loops - ucsbkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · common error: infinite...

126
Chapter 4: Loops

Upload: others

Post on 07-Oct-2020

1 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

Chapter4:Loops

Page 2: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

ChapterGoals• Toimplementwhileandforloops

• Tohand-tracetheexecutionofaprogram

• Tobecomefamiliarwithcommonloopalgorithms

• Tounderstandnestedloops

• Toimplementprogramsthatreadandprocessdatasets

• Touseacomputerforsimulations

Inthischapter,youwilllearnaboutloopstatementsinPython,aswellastechniquesforwritingprogramsthatsimulateactivitiesinthereal

world.

24/6/16

Page 3: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

Contents• Thewhile loop

• ProblemSolving:Hand-Tracing

• Application:ProcessingSentinels

• ProblemSolving:Storyboards

• CommonLoopAlgorithms

• Thefor loop

• Nestedloops

• ProcessingStrings

• Application:RandomNumbersandSimulation

• Graphics:DigitalImageProcessing

• ProblemSolving:SolveaSimplerProblemFirst

34/6/16

Page 4: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

Thewhile Loop

4/6/16 4

Page 5: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

Thewhile Loop• Examplesofloopapplications

• Calculatingcompoundinterest• Simulations,eventdrivenprograms• Drawingtiles…

• Compoundinterestalgorithm(Chapter1)

Steps

54/6/16

Page 6: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

Planningthewhile Loopbalance=10.0target=100.0year=0rate=0.025whilebalance<TARGET:year=year+1interest=balance*RATE/100balance=balance+interest

AloopexecutesinstructionsrepeatedlywhileaconditionisTrue.

64/6/16

Page 7: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

Syntax:while Statement

74/6/16

Page 8: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

Count-ControlledLoops• Awhile loopthatiscontrolledbyacounter

counter = 1 # Initialize the counter

while counter <= 10 : # Check the counterprint(counter)counter = counter + 1 # Update the loop variable

84/6/16

Page 9: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

Event-ControlledLoops• Awhile loopthatiscontrolledbyacounter

balance = INITIAL_BALANCE # Initialize the loop variable

while balance <= TARGET: # Check the loop variableyear – year + 1balance = balance * 2 # Update the loop variable

94/6/16

Page 10: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

ExecutionoftheLoop

104/6/16

Page 11: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

ExecutionoftheLoop(2)

114/6/16

Page 12: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

Doubleinv.py

Declare andinitialize avariableoutsideofthe looptocountyear

Increment theyear variableeach timethrough

124/6/16

Page 13: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

Investment Example• Openthefile:

• Doubleinv.py

• Runtheprogramwithseveraltestcases• Theprogramwillpromptyouforarate• Enteramixofvalidandinvalidrates

134/6/16

Page 14: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

while LoopExamples

144/6/16

Page 15: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

while LoopExamples (2)

154/6/16

Page 16: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

CommonError: IncorrectTestCondition• TheloopbodywillonlyexecuteifthetestconditionisTrue.

• IfbalisinitializedaslessthantheTARGETandshouldgrowuntilitreachesTARGET• Whichversionwillexecute the loopbody?

while bal < TARGET :year = year + 1interest = bal * RATEbal = bal + interest

while bal >= TARGET :year = year + 1interest = bal * RATEbal = bal + interest

164/6/16

Page 17: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

CommonError:InfiniteLoops• TheloopbodywillexecuteuntilthetestconditionbecomesFalse.

• Whatifyouforgettoupdatethetestvariable?• bal isthetestvariable (TARGET doesn’t change)• Youwill loopforever!(oruntilyoustoptheprogram)

while bal < TARGET :year = year + 1interest = bal * RATEbal = bal + interest

174/6/16

Page 18: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

CommonError:Off-by-OneErrors• A‘counter’variableisoftenusedinthetestcondition

• Yourcountercanstartat0or1,butprogrammersoftenstartacounterat0

• IfIwanttopaintall5fingersononehand,whenIamdone?• Ifyoustartat0,use“<“ Ifyoustartat1,use“<=“• 0,1,2,3,4 1,2,3,4,5

finger = 0FINGERS = 5while finger < FINGERS :

# paint fingerfinger = finger + 1

finger = 1FINGERS = 5while finger <= FINGERS :

# paint fingerfinger = finger + 1

184/6/16

Page 19: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

HandTracingLoops

4/6/16 19

Page 20: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

Hand-Tracing Loops• Example:Calculatethesumofdigits(1+7+2+9)

• Makecolumnsforkeyvariables(n,total,digit)• Examinethecodeandnumberthesteps• Setvariablestostatebeforeloopbegins

204/6/16

Page 21: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

TracingSumofDigits

• Startexecutingloopbodystatementschangingvariablevaluesonanewline• Crossoutvaluesinpreviousline

214/6/16

Page 22: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

TracingSumofDigits

• Continueexecutingloopstatementschangingvariables• 1729/10leaves172(noremainder)

224/6/16

Page 23: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

TracingSumofDigits• Testcondition.IfTrue,executeloopagain

• Variablenis172,Is172>0?,True!

• Makeanewlineforthesecondtimethroughandupdatevariables

234/6/16

Page 24: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

TracingSumofDigits• Thirdtimethrough

• Variablenis17whichisstillgreaterthan0

• Executeloopstatementsandupdatevariables

244/6/16

Page 25: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

TracingSumofDigits• Fourthloopiteration:

• Variablenis1atstartofloop.1>0?True• Executesloopandchangesvariablento0(1/10=0)

254/6/16

Page 26: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

TracingSumofDigits• Becausenis0,theexpression(n>0)isFalse

• Loopbodyisnotexecuted• Jumpstonextstatementaftertheloopbody

• Finallyprintsthesum!

264/6/16

Page 27: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

Summaryofthewhile Loop• while loopsareverycommon

• Initializevariablesbeforeyoutest• TheconditionistestedBEFOREtheloopbody

• Thisiscalledpre-test• Theconditionoftenusesacountervariable

• Somethinginsidetheloopshouldchangeoneofthevariablesusedinthetest

• Watchoutforinfiniteloops!

274/6/16

Page 28: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

SentinelValues

4/6/16 28

Page 29: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

ProcessingSentinelValues• Sentinelvaluesareoftenused:

• Whenyoudon’tknowhowmanyitems are inalist,usea‘special’characterorvaluetosignalthe “last” item

• Fornumeric inputofpositive numbers, it iscommon tousethevalue-1

Asentinelvaluedenotestheendofadataset,butitisnotpartofthedata.

salary = 0.0while salary >= 0 :

salary = float(input())if salary >= 0.0 :

total = total + salarycount = count + 1

294/6/16

Page 30: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

AveragingaSetofValues• Declareandinitializea‘total’variableto0

• Declareandinitializea‘count’variableto0

• Declareandinitializea‘salary’variableto0

• Promptuserwithinstructions

• Loopuntilsentinelvalueisentered• Saveenteredvaluetoinputvariable(‘salary’)• Ifsalaryisnot-1orless(sentinelvalue)

• Addsalaryvariabletototalvariable• Add1tocountvariable

• Makesureyouhaveatleastoneentrybeforeyoudivide!• Dividetotalbycountandoutput.• Done!

304/6/16

Page 31: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

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

314/6/16

Page 32: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

Sentinel.py (2)

Prevent divide by 0

Calculate and output the average salary using the total and countvariables

324/6/16

Page 33: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

SentinelExample• Openthefile:

• Sentinal.py

• NoticetheuseoftheIF() testinsidethewhile loop• TheIF()checkstomakesurewearenotprocessingthesentinelvalue

334/6/16

Page 34: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

PrimingRead• Someprogrammersdon’tlikethe“trick”ofinitializingtheinputvariablewithavalueotherthanasentinel.

# Set salary to a value to ensure that the loop # executes at least once.salary = 0.0while salary >= 0 :

salary = float(input("Enter a salary or -1 to finish: "))while salary >= 0 :

344/6/16

• Analternativeistochangethevariablewithareadbeforetheloop.

Page 35: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

ModificationRead• Theinputoperationatthebottomoftheloopisusedtoobtainthenextinput.

# Priming readsalary = float(input("Enter a salary or -1 to finish: "))while salary >= 0.0 :

total = total + salarycount = count + 1# Modification readsalary = float(input("Enter a salary or -1 to finish: "))

354/6/16

Page 36: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

BooleanVariablesandSentinels• Abooleanvariablecanbeusedtocontrolaloop

• Sometimescalleda‘flag’variable

done = Falsewhile not done :

value = float(input("Enter a salary or -1 to finish: "))if value < 0.0:

done = Trueelse :

# Process value

Initialize done so that the loop will execute

Set done ‘flag’ to True if sentinel value is found

364/6/16

Page 37: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

Storyboards

4/6/16 37

Page 38: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

Storyboards• Oneusefulproblemsolvingtechniqueistheuseofstoryboardstomodeluserinteraction.Itcanhelpanswer:• Whatinformationdoestheuserprovide,andinwhichorder?• Whatinformationwillyourprogramdisplay,andinwhichformat?• Whatshouldhappenwhenthereisanerror?• Whendoestheprogramquit?

• Astoryboardconsistsofannotatedsketchesforeachstepinanactionsequence.

384/6/16

Page 39: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

StoryboardExample• Goal:Convertingasequenceofvalues

• Willrequirealoopandsomevariables• Handleoneconversioneachtimethroughtheloop

394/6/16

Page 40: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

WhatCanGoWrong?Unknownunittypes

• Whatistheusermisspellscentimetersandinches?• Whatotherconversionsareavailable?• Solution:

• Showalistoftheacceptableunittypes

404/6/16

Page 41: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

WhatElseCanGoWrong?• Howdoestheuserquittheprogram?

• Storyboardshelpyouplanaprogram• Knowingtheflowhelps youstructure yourcode

414/6/16

Page 42: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

CommonLoopAlgorithms

4/6/16 42

Page 43: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

CommonLoopAlgorithms1. SumandAverageValue

2. CountingMatches

3. PromptinguntilaMatchIsFound

4. MaximumandMinimum

5. ComparingAdjacentValues

434/6/16

Page 44: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

AverageExampletotal = 0.0count = 0inputStr = input("Enter value: ")while inputStr != "" :

value = float(inputStr)total = total + valuecount = count + 1inputStr = input("Enter value: ")

if count > 0 : average = total / count

else :average = 0.0

AverageofValues• Firsttotalthevalues• Initializecount to0

• Incrementperinput• Checkforcount 0

• Beforedivide!

444/6/16

Page 45: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

SumExample• SumofValues

• Initializetotalto0• Usewhileloopwithsentinel

total = 0.0inputStr = input("Enter value: ")while inputStr != "" :

value = float(inputStr)total = total + valueinputStr = input("Enter value: ")

454/6/16

Page 46: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

CountingMatches(e.g.,NegativeNumbers)

negatives = 0inputStr = input("Enter value: ")while inputStr != "“ :

value = int(inputStr)if value < 0 :

negatives = negatives + 1inputStr = input("Enter value: ")

print("There were", negatives, "negative values.")

• CountingMatches• Initializenegatives to0• Useawhile loop• Addtonegatives permatch

464/6/16

Page 47: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

PromptUntilaMatchisFound• InitializebooleanflagtoFalse

• Testsentinelinwhileloop• Getinput,andcomparetorange

• Ifinputisinrange,changeflagtoTrue• Loopwillstopexecuting

valid = Falsewhile not valid :

value = int(input("Please enter a positive value < 100: "))if value > 0 and value < 100 :

valid = Trueelse :

print("Invalid input.")

47

Thisisanexcellentwaytovalidateuseprovidedinputs

4/6/16

Page 48: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

Maximum• Getfirstinputvalue

• Bydefinition,thisisthelargestthatyouhaveseensofar

• Loopwhileyouhaveavalidnumber(non-sentinel)• Getanotherinputvalue• Comparenewinputtolargest(orsmallest)• Updatelargestifnecessary

largest = int(input("Enter a value: "))inputStr = input("Enter a value: ")while inputStr != "“ :

value = int(inputStr)if value > largest :

largest = valueinputStr = input("Enter a value: ")

484/6/16

Page 49: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

Minimum• Getfirstinputvalue

• Thisisthesmallestthatyouhaveseensofar!

• Loopwhileyouhaveavalidnumber(non-sentinel)• Getanotherinputvalue• Comparenewinputtolargest(orsmallest)• Updatesmallestifnecessary

smallest = int(input("Enter a value: "))inputStr = input("Enter a value: ")while inputStr != "“ :

value = int(inputStr)if value < smallest :

smallest = valueinputStr = input("Enter a value: ")

494/6/16

Page 50: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

ComparingAdjacentValues• Getfirstinputvalue

• Usewhile todetermineiftherearemoretocheck• Copyinputtopreviousvariable• Getnextvalueintoinputvariable• Compareinputtoprevious,andoutputifsame

value = int(input("Enter a value: "))inputStr = input("Enter a value: ")while inputStr != "“ :

previous = valuevalue = int(inputStr)if value == previous :

print("Duplicate input")inputStr = input("Enter a value: ")

504/6/16

Page 51: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

GradesExample• Openthefile:

• Grades.py

• Lookcarefullyatthesourcecode.

• Themaximumpossiblescoreisreadasuserinput• Thereisalooptovalidatetheinput

• Thepassinggradeiscomputedas60%oftheavailablepoints

514/6/16

Page 52: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

Thefor Loop

4/6/16 52

Page 53: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

Thefor Loop• Usesofafor loop:

• Thefor loopcanbeusedtoiterateoverthecontentsofanycontainer.

• Acontainer isisanobject(Likeastring)thatcontainsorstoresacollectionofelements

• Astring isacontainerthatstoresthecollectionofcharactersinthestring

534/6/16

Page 54: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

AnExampleofafor Loop

stateName = "Virginia"i = 0while i < len(stateName) :

letter = stateName[i]print(letter)i = i + 1

whileversion

stateName = "Virginia"for letter in stateName :

print(letter) forversion

• Noteanimportantdifferencebetweenthewhileloopandtheforloop.• Inthewhileloop,theindexvariablei isassigned0,1,andsoon.• Intheforloop,theelementvariableisassignedstateName[0],stateName[1],andsoon.

544/6/16

Page 55: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

TheforLoop(2)• Usesofaforloop:

• Aforloopcanalsobeusedasacount-controlledloopthatiteratesoverarangeofintegervalues.

i = 1while i < 10 :

print(i)i = i + 1

for i in range(1, 10) : print(i)

while version

for version

554/6/16

Page 56: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

Syntaxofafor Statement (Container)• Usingaforlooptoiterateoverthecontentsofacontainer,anelementatatime.

564/6/16

Page 57: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

Syntaxofafor Statement (Range)• Youcanuseaforloopasacount-controlledlooptoiterateoverarangeofintegervalues

• Weusetherangefunctionforgeneratingasequenceofintegersthatlessthantheargumentthatcanbeusedwiththeforloop

574/6/16

Page 58: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

Planningafor Loop• Printthebalanceattheendofeachyearforanumberofyears

584/6/16

Page 59: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

GoodExamplesoffor Loops• Keeptheloopssimple!

594/6/16

Page 60: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

Investment Example

604/6/16

Page 61: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

ProgrammingTip• Findingthecorrectlowerandupperboundsforaloopcanbeconfusing.• Shouldyoustartat0orat1?• Shouldyouuse<=bor<basaterminationcondition?

• Countingiseasierforloopswithasymmetricbounds.• Thefollowingloopsareexecutedb- atimes.

int i = awhile i < b :

. . .i = i + 1

for i in range(a, b) :. . .

614/6/16

Page 62: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

ProgrammingTip• Theloopwithsymmetricbounds(“<=”,isexecutedb- a+1times.

• That“+1”isthesourceofmanyprogrammingerrors.

i = awhile i <= b :

. . .i = i + 1

# For this version of the loop the ‘+1’ is very noticeable!for year in range(1, numYears + 1) :

624/6/16

Page 63: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

Summaryofthefor Loop• for loopsareverypowerful

• Thefor loopcanbeusedtoiterateoverthecontentsofanycontainer,whichisanobjectthatcontainsorstoresacollectionofelements• astring isacontainer thatstoresthecollection ofcharacters inthestring.

• Afor loopcanalsobeusedasacount-controlledloopthatiteratesoverarangeofintegervalues.

634/6/16

Page 64: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

StepstoWriting aLoop• Planning:

• Decidewhatworktodoinsidetheloop• Specifytheloopcondition• Determinelooptype• Setupvariablesbeforethefirstloop• Processresultswhentheloopisfinished• Tracetheloopwithtypicalexamples

• Coding:• ImplementtheloopinPython

644/6/16

Page 65: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

ASpecialFormoftheprint Function• Pythonprovidesaspecialformoftheprintfunctionthatdoesnotstartanewlineaftertheargumentsaredisplayed

• Thisisusedwhenwewanttoprintitemsonthesamelineusingmultipleprintstatements

• Forexamplethetwostatements:

print(“00”, end=””)print(3 + 4)

• Producetheoutput:

007

• Includingend=“” asthelastargumenttotheprintfunctionprintsanemptystringafterthearguments,insteadonanewline

• Theoutputofthenextprint functionstartsonthesameline

4/6/16 65

Page 66: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

NestedLoops

4/6/16 66

Page 67: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

LoopsInsideofLoops• InChapterThreewelearnedhowtonestif statementstoallowustomakecomplexdecisions• Rememberthattonesttheif statementsweneedtoindentthecodeblock

• Complexproblemssometimesrequireanestedloop,oneloopnestedinsideanotherloop• Thenestedloopwillbeindentedinsidethecodeblockofthefirstloop

• Agoodexampleofusingnestedloopsiswhenyouareprocessingcellsinatable• Theouterloopiteratesoveralloftherowsinthetable• Theinnerloopprocessesthecolumnsinthecurrentrow

4/6/16 67

Page 68: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

OurExampleProblemStatement• PrintaTableHeaderthatcontainsx1,x2,x3,andx4

• PrintaTablewithfourcolumnsandtenrowsthatcontainthepowersofx1,x2,x3,andx4 forx=1to10

4/6/16 68

Page 69: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

ApplyingNestedLoops• Howwouldyouprintatablewithrowsandcolumns?

• Printtopline(header)• Useaforloop

• Printtablebody…• Howmanyrowsareinthetable?• Howmanycolumnsinthetable?

• Loopperrow• Looppercolumn

• Inourexamplethereare:• Fourcolumnsinthetable• Tenrowsinthetable

4/6/16 69

Page 70: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

PseudocodetoPrinttheTablePrintthetableheader

for x from 1 to 10print a new table rowprint a new line

• Howdoweprintatablerow?

For n from 1 to 4print xn

• Wehavetoplacethisloopinsidetheprecedingloop• Theinnerloopis“nested”insidetheouterloop

4/6/16 70

Page 71: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

PseudocodetoPrinttheTablePrintthetableheader:

for x from 1 to 10for n from 1 to 4print Xn

print a new line

4/6/16 71

n è

Page 72: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

InnerLoop

FlowchartofaNestedLoopx=1

x<=10?

n=1

n<=4?

Printxn

n=n+1

Printnewline

x=x+1

True

False True

Done

False

4/6/16 72

Page 73: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

Powertable.py

4/6/16 73

Bodyofouterloop,x=1è 10

Bodyofinnerloop,n=1è 4

The end=“” suppresses the new line, so the numbers are all printed on the same line

Page 74: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

TheResults

4/6/16 74

Page 75: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

FirstExercise• Opentheprogram:

• powertable.py

• Runtheprogramandreviewtheresults

• Makethefollowingchanges:• ChangethevalueofNMAXto6andruntheprogram• Whatchangesinthetable?• ChangethevalueofNMAXbackto4• ChangethevalueofXMAXto4• Whatchangesinthetable?

4/6/16 75

Page 76: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

NestedLoopExamples

4/6/16 76

Page 77: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

HandTracingtheLoop

• i willhavethevalues:• 0,1,2,3– Sowewillhavefourlinesofstars

• j willhavethevalues• 0- Sowewillhaveonestar• 0,1- Sowewillhavetwostars• 0,1,2- Sowewillhavethreestars• 0,1,2,3- Sowewillhavefourstars

4/6/16 77

Page 78: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

NestedLoopExamples (2)

4/6/16 78

Page 79: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

SecondProblemStatement• Printthefollowingpatternofbrackets:[][][][][][][][][][][][]

• Thepatternconsistsof:• Threerows• Eachrowhasfourpairsofbrackets

• Whatdoweknow?• Weneedtwonestedloops

• Thefirstloop(theouterloop)willprinteachofthethreerows• Thesecondloop(theinnerloop)willprintthefourpairsofbrackets

4/6/16 79

Page 80: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

PseudocodeCode,ResultsFor i = 1 to 3For j = 1 to 4Print “[]”

Print a new line

4/6/16 80

Page 81: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

ExamAveragesProblemStatement• Itiscommontorepeatedlyreadandprocessmultiplegroupsofvalues:

• Writeaprogramthatcancomputetheaverageexamgradeformultiplestudents.

• Eachstudenthasthesamenumberofexamgrades• Prompttheuserforthenumberofexams• Whenyoufinishastudentprompttheusertoseeiftherearemorestudentstoprocess

• Whatdoweknow?

• Whatdoweneedtocompute?

• Whatisouralgorithm/approach?

4/6/16 81

Page 82: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

StepOne:UnderstandtheProblem• Tocomputetheaveragegradeforastudent,wemustreadandtallyallofthegradesforthatstudent• Wecanusealooptodothis.(wehaveworkingcodetodothisportion)

• Weneedtocomputegradesformultiplestudents• ThatimpliesasetofnestedLoops

• Theouterloopprocesseseachstudent• Theinnerloopprocessthestudent’sgrades

4/6/16 82

Page 83: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

StepTwo• Computethegradeforonestudent

• Setupthevariablesandloop

• Weknowhowmanygradestoprocess,sowecanuseacount-controlledloop

total score = 0For i in range (1, number of exams + 1) :Read the next exam scoreAdd the exam score to the total score

Compute the exam averagePrint the exam average

4/6/16 83

Page 84: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

StepThree• Repeattheprocessforeachstudent

• Sincewedon’tknowhowmanystudentsthereare,wewilluseawhileloopwithasentinelvalue• Forsimplicitywewilluse“Y”asthesentinelvalue

4/6/16 84

Page 85: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

StepFour:Translate toPython

4/6/16 85

Page 86: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

ExamAverages Example• Openthefile:

• examaverages.py

• Noticethatthesecondloop(thefor loop)isnestedinsidethewhile loop

• Youshouldseealine(theindentguide)connectingthefor looponline17downtothestatementonline21• Thelineisshowingyouthestatementsthatareincludedinthefor loop

• Ifyoudon’tseetheindentguide:• Clickontheedittab• Select“Preferences…”• UnderEditor,selectIndention• Clickthe“ShowIndentGuides”box• ClicktheApplybutton• ClicktheOkayButton

4/6/16 86

Page 87: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

TurningtheIndentGuidesOn

4/6/16 87

Page 88: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

ProcessingStrings• Acommonuseofloopsistoprocessorevaluatestrings.

• Forexample,youmayneedtocountthenumberofoccurrencesofoneormorecharactersinastringorverifythatthecontentsofastringmeetcertaincriteria.

4/6/16 88

Page 89: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

ProcessingStrings

4/6/16 89

Page 90: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

StringProcessingExamples• CountingMatches

• FindingAllMatches

• FindingtheFirstorLastMatch

• ValidatingaString

• BuildingaNewString

4/6/16 90

Page 91: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

CountingMatches• Supposeyouneedtocountthenumberofuppercaseletterscontainedinastring.

• Wecanuseaforlooptocheckeachcharacterinthestringtoseeifitisuppercase

• Theloopbelowsetsthevariablecharequaltoeachsuccessivecharacterinthestring

• Eachpassthroughtheloopteststhenextcharacterinthestringtoseeifitisuppercase

uppercase = 0for char in string :

if char.isupper() :uppercase = uppercase + 1

4/6/16 91

Page 92: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

CountingVowels• Supposeyouneedtocountthevowelswithinastring

• Wecanuseaforlooptocheckeachcharacterinthestringtoseeifitisinthestringofvowels“aeiuo”

• Theloopbelowsetsthevariablecharequaltoeachsuccessivecharacterinthestring

• Eachpassthroughtheloopteststhelowercaseofthenextcharacterinthestringtoseeifitisinthestring“aeiou”

vowels = 0for char in word :

if char.lower() in "aeiou" :vowels = vowels + 1

4/6/16 92

Page 93: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

FindingAllMatchesExample• Whenyouneedtoexamineeverycharacterinastring,independentofitspositionwecanuseaforstatementtoexamineeachcharacter

• Ifweneedtoprintthepositionofeachuppercaseletterinasentencewecantesteachcharacterinthestringandprintthepositionofalluppercasecharacters

• Wesettherangetobethelengthofthestring• Wetesteachcharacter• Ifit isuppercase weprintI,its position inthestring

sentence = input("Enter a sentence: ")for i in range(len(sentence)) :

if sentence[i].isupper() :print(i)

4/6/16 93

Page 94: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

FindingtheFirstMatch• Thisexamplefindsthepositionofthefirstdigitinastring.

found = Falseposition = 0while not found and position < len(string) :

if string[position].isdigit() :found = True

else :position = position + 1

if found :print("First digit occurs at position", position)

else :print("The string does not contain a digit.")

4/6/16 94

Page 95: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

FindingtheLastMatch• Hereisaloopthatfindsthepositionofthelastdigitinthestring.

• Thisapproachusesawhilelooptostartatthelastcharacterinastringandtesteachvaluemovingfromtheendofthestringtothestartofthestring• Position issettothe length ofthestring - 1• Ifthecharacter isnotadigit,wedecrease position by1• Untilwefindadigit,orprocessall thecharacters

found = Falseposition = len(string) - 1while not found and position >= 0 :

if string[position].isdigit() :found = True

else :position = position - 1

4/6/16 95

Page 96: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

ValidatingaString• IntheUnitedStates,telephonenumbersconsistofthreeparts––areacodeexchange,andlinenumber––whicharecommonlyspecifiedintheform(###)###-####.

4/6/16 96

Page 97: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

ValidatingaString (code)• Wecanexamineastringtoensurethatitcontainsacorrectlyformattedphonenumber.(e.g.,(703)321-6753)

• Thelooptesteachcharactertoseeititiscorrectforitsposition,oranumber

valid = len(string) == 13position = 0while valid and position < len(string) :

valid = ((position == 0 and string[position] != "(")or (position == 4 and string[position] != ")")or (position == 8 and string[position] != "-")or (position != 0 and position != 4 and position != 8

and string[position].isdigit())) :position = position + 1

4/6/16 97

Page 98: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

Building aNewString• Oneoftheminorannoyancesofonlineshoppingisthatmanywebsitesrequireyoutoenteracreditcardwithoutspacesordashes,whichmakesdouble-checkingthenumberrathertedious.

• Howhardcanitbetoremovedashesorspacesfromastring?

4/6/16 98

Page 99: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

Building aNewString (code)• Thecontentsofastringcannotbechanged.

• Butnothingpreventsusfrombuildinganewstring.

• Hereisaloopthatbuildsanewstringcontainingacreditcardnumberwithspacesanddashesremoved:• Wereadthecreditcardnumber• Weinitializeanewstringtotheemptystring• Wetesteachcharacterintheuserinput

• Ifthecharacterisnotaspaceordashweappendittothenewstring

userInput = input("Enter a credit card number: ")creditCardNumber = ""for char in userInput :

if char != " " and char != "-" :creditCardNumber = creditCardNumber + char

4/6/16 99

Page 100: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

Application: RandomNumbersandSimulations

4/6/16 100

Page 101: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

RandomNumbers/Simulations• Gamesoftenuserandomnumberstomakethingsinteresting

• RollingDice• Spinningawheel• Pickacard

• Asimulationusuallyinvolvesloopingthroughasequenceofevents• Days• Events

4/6/16 101

Page 102: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

GeneratingRandomNumbers• ThePythonlibraryhasarandomnumbergeneratorthatproducesnumbersthatappear toberandom• Thenumbersarenotcompletelyrandom.Thenumbersaredrawnfromasequenceofnumbersthatdoesnotrepeatforalongtime

• random()returnsanumberthatis>=0and<1

4/6/16 102

Page 103: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

SimulatingDieTosses• Goal:

• Togeneratearandomintegerinagivenrangeweusetherandint()function

• Randinthastwoparameters,therange(inclusive)ofnumbersgenerated

4/6/16 103

Page 104: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

TheMonteCarloMethod• Usedtofindapproximatesolutionstoproblemsthatcannotbepreciselysolved

• Example:ApproximatePIusingtherelativeareasofacircleinsideasquare• Usessimplearithmetic• Hitsareinsidecircle• Triesaretotalnumberoftries• Ratiois4xHits/Tries

4/6/16 104

Page 105: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

MonteCarloExample

4/6/16 105

Page 106: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

ImageProcessing

4/6/16 106

Page 107: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

Manipulating Images• Digitalimageprocessingistheuseofalgorithmstomanipulatedigitalimages

• Itisusedin:• Digital photography• Datacompression• Computer graphics• Computer vision• Robotics

• We’lllearnhowtomanipulateimageswiththeezgraphics package

4/6/16 107

Page 108: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

Representing Images• Adigitalimageiscomposedofpixelsarrangedinagridofrowsandcolumns• Computer images appear “smooth” because verysmallpoints onthescreen(veryclose together) areused toreproducethe individual pixels

• Pixelsstoredatarepresentingacolorfromthevisualspectrum• Thediscrete RGBcolormodel isthemostusedmodel• Thethree individual colorsarespecified bytheamount ofred,green,andblue light needed toproduceagivencolor

• Thevaluesaregivenas integers between 0(nolightpresent) and255(maximum light present)

4/6/16 108

Page 109: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

FilteringanImage• Filteringanimagemodifiesthecolorcomponentvaluesofeachpixelinsomeway

4/6/16 109

Page 110: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

ProcessinganImage• Westartbyloadingtheimageintoourprogram

• Inezgraphicsanimage isstored inaninstance oftheGraphicsImage classfilename = "queen-mary.gif"image = GraphicsImage(filename)

• WedrawtheimageonthecanvasofaGraphicsWindowwin = GraphicsWindow()canvas = win.canvas()canvas.drawImage(image)win.wait()

4/6/16 110

Page 111: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

FilteringanImage• Tofilteranimage,youmustgetthered,green,andbluecomponentvaluesforeachpixel.• Thepixels areorganized intoatwo-dimensional gridofsizewidth× height:• Therowsandcolumns arenumbered sequentially startingat0,withpixel(0,0)intheupper-left corner.

• Therownumbers rangefrom0toheight– 1;thecolumnnumbers from0towidth– 1.

4/6/16 111

Page 112: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

AccessingtheComponentValuesofaPixel• WeusethegetRed,getGreen andgetBluemethodsred = image.getRed(0, 4)green = image.getGreen(0, 4)blue = image.getBlue(0, 4)

• Tocreatethenegativeofanimage:

newRed = 255 - rednewGreen = 255 - greennewBlue = 255 – blue

• Andthenupdatethepixel

image.setPixel(0,4,newRed,newGreen,newBlue)

4/6/16 112

Page 113: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

ThePseudocodewidth = image.width()height = image.height()for row in range(height) :

for col in range(width) :Get the current pixel color.Filter the pixel.Set the pixel to the new color.

image.save("negative" + filename)

4/6/16 113

Page 114: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

GraphicsImage Methods

4/6/16 114

Page 115: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

ProblemSolving:SolveaSimplerProblemFirst

4/6/16 115

Page 116: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

SimplifyaComplexProblem• Aswelearnmoreaboutprogramming,thecomplexityofthetaskswearesolvingincreases

• Whenwearefacedwithacomplextaskweshouldapplyacriticalskill:• Simplifying theproblem andsolving thesimpler problem first

• Oursimplification(AKAproblemdecomposition)skillsimprovewithpractice

4/6/16 116

Page 117: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

ASampleProblem• Ourassignmentistoarrangepictures,liningthemupalongthetopedges,separatingthemwithsmallgaps,andstartinganewrowwheneveryourunoutofroominthecurrentrow.• Thissounds simple, right?

4/6/16 117

Page 118: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

ASimplePlan• Let’sdevelopaplanthatsolvesasetofsimpler(increasingincomplexity)problems

4/6/16 118

Page 119: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

Increase theComplexity

4/6/16 119

Page 120: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

ImplementingOurPlan1. Specifythecanvascoordinateswheretheupperleftcornerofthefirst

imageshouldbeplaced

2. Thenplacethenextpictureafterthefirstafterthefirst• Itneedstobedrawnsothatitsleft-mostedgeispositionedattheright-mostx-coordinateoftheprecedingpicture

• Thiscanbedeterminedbyobtainingthewidthofthefirstpictureandusingthatvalueasthex-coordinateforthesecondpicture

3. Separatethetwopictureswithagap

4. Todrawthethirdpicture,it’snotsufficienttoknowthewidthoftheprecedingpicture.• Wealsoneedtoknowthex-coordinatewhereitwasdrawnsowecanaddthatvaluetothewidthoftheprecedingimage,plusthegapbetweentheimages

4/6/16 120

Page 121: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

ImplementingourPlan5. Nowlet’sputallofthepicturesinarow

• Loadthepicturesinaloop,andthenputeachpicturetotherightoftheonethatprecededit.

• Ineachiteration,youneedtotracktwopictures:theonethatisbeingloaded,andtheonethatprecededit

6. Wedon’twanttohaveallpicturesinasinglerow• TherightmarginofapictureshouldnotextendpastMAX_WIDTH• Iftheimagedoesn’tfitweneedtoputitonthenextrow,belowallthepicturesinthecurrentrow

• We’llsetavariablemaxY tothemaximumy-coordinateofallplacedpictures,updatingitwheneveranewpictureisplaced

4/6/16 121

Page 122: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

Summary

4/6/16 122

Page 123: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

Summary: TwoTypesofLoops• while Loops

• for Loops

• while loopsareverycommonlyused(generalpurpose)

• Usesofthefor loop:• Thefor loopcanbeusedtoiterateoverthecontentsofanycontainer.

• Afor loopcanalsobeusedasacount-controlledloopthatiteratesoverarangeofintegervalues.

1234/6/16

Page 124: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

Summary• Eachlooprequiresthefollowingsteps:

• Initialization(setupvariablestostartlooping)• Condition(testifweshouldexecuteloopbody)• Update(changesomethingeachtimethrough)

• AloopexecutesinstructionsrepeatedlywhileaconditionisTrue.

• Anoff-by-oneerrorisacommonerrorwhenprogrammingloops.• Thinkthroughsimpletestcasestoavoidthistypeoferror.

1244/6/16

Page 125: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

Summary• Asentinelvaluedenotestheendofadataset,butitisnotpartofthedata.

• Youcanuseabooleanvariabletocontrolaloop.• SetthevariabletoTrue beforeenteringtheloop• SetittoFalse toleavetheloop.

• Loopscanbeusedinconjunctionwithmanystringprocessingtasks

1254/6/16

Page 126: Chapter 4: Loops - UCSBkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · Common Error: Infinite Loops • The loop body will execute until the test condition becomes False. • What

Summary• Inasimulation,youusethecomputertosimulateanactivity.

• Youcanintroduce randomness bycallingtherandomnumbergenerator.

4/6/16 126