+ All Categories
Home > Documents > Common Loop Algorithms - Westmont Collegedjp3.westmont.edu/.../Lectures/Lecture_10_01.pdfCommon Loop...

Common Loop Algorithms - Westmont Collegedjp3.westmont.edu/.../Lectures/Lecture_10_01.pdfCommon Loop...

Date post: 24-Mar-2020
Category:
Upload: others
View: 2 times
Download: 0 times
Share this document with a friend
52
Common Loop Algorithms 9/21/16 42
Transcript
Page 1: Common Loop Algorithms - Westmont Collegedjp3.westmont.edu/.../Lectures/Lecture_10_01.pdfCommon Loop Algorithms 1. Sum and Average Value 2. Coun4ng Matches 3. Promp4ng un4l a Match

Common Loop Algorithms

9/21/16 42

Page 2: Common Loop Algorithms - Westmont Collegedjp3.westmont.edu/.../Lectures/Lecture_10_01.pdfCommon Loop Algorithms 1. Sum and Average Value 2. Coun4ng Matches 3. Promp4ng un4l a Match

Common Loop Algorithms 1.  SumandAverageValue

2.  Coun4ngMatches

3.  Promp4ngun4laMatchIsFound

4. MaximumandMinimum

5.  ComparingAdjacentValues

43 9/21/16

Page 3: Common Loop Algorithms - Westmont Collegedjp3.westmont.edu/.../Lectures/Lecture_10_01.pdfCommon Loop Algorithms 1. Sum and Average Value 2. Coun4ng Matches 3. Promp4ng un4l a Match

Sum Example •  SumofValues

•  Ini4alizetotalto0•  Usewhileloopwithsen4nel

total=0.0inputStr=input("Entervalue:")whileinputStr!="":value=float(inputStr)total=total+valueinputStr=input("Entervalue:")

44 9/21/16

Page 4: Common Loop Algorithms - Westmont Collegedjp3.westmont.edu/.../Lectures/Lecture_10_01.pdfCommon Loop Algorithms 1. Sum and Average Value 2. Coun4ng Matches 3. Promp4ng un4l a Match

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

Page 5: Common Loop Algorithms - Westmont Collegedjp3.westmont.edu/.../Lectures/Lecture_10_01.pdfCommon Loop Algorithms 1. Sum and Average Value 2. Coun4ng Matches 3. Promp4ng un4l a Match

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

Page 6: Common Loop Algorithms - Westmont Collegedjp3.westmont.edu/.../Lectures/Lecture_10_01.pdfCommon Loop Algorithms 1. Sum and Average Value 2. Coun4ng Matches 3. Promp4ng un4l a Match

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

Page 7: Common Loop Algorithms - Westmont Collegedjp3.westmont.edu/.../Lectures/Lecture_10_01.pdfCommon Loop Algorithms 1. Sum and Average Value 2. Coun4ng Matches 3. Promp4ng un4l a Match

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

Page 8: Common Loop Algorithms - Westmont Collegedjp3.westmont.edu/.../Lectures/Lecture_10_01.pdfCommon Loop Algorithms 1. Sum and Average Value 2. Coun4ng Matches 3. Promp4ng un4l a Match

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

Page 9: Common Loop Algorithms - Westmont Collegedjp3.westmont.edu/.../Lectures/Lecture_10_01.pdfCommon Loop Algorithms 1. Sum and Average Value 2. Coun4ng Matches 3. Promp4ng un4l a Match

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

Page 10: Common Loop Algorithms - Westmont Collegedjp3.westmont.edu/.../Lectures/Lecture_10_01.pdfCommon Loop Algorithms 1. Sum and Average Value 2. Coun4ng Matches 3. Promp4ng un4l a Match

Grades Example •  Openthefile:

•  Grades.py

•  Lookcarefullyatthesourcecode.•  Themaximumpossiblescoreisreadasuserinput

•  Thereisalooptovalidatetheinput

•  Thepassinggradeiscomputedas60%oftheavailablepoints

51 9/21/16

Page 11: Common Loop Algorithms - Westmont Collegedjp3.westmont.edu/.../Lectures/Lecture_10_01.pdfCommon Loop Algorithms 1. Sum and Average Value 2. Coun4ng Matches 3. Promp4ng un4l a Match

The for Loop

9/21/16 52

Page 12: Common Loop Algorithms - Westmont Collegedjp3.westmont.edu/.../Lectures/Lecture_10_01.pdfCommon Loop Algorithms 1. Sum and Average Value 2. Coun4ng Matches 3. Promp4ng un4l a Match

The for Loop •  Usesofaforloop:

•  Theforloopcanbeusedtoiterateoverthecontentsofanycontainer.

•  Acontainerisanobject(Likeastring)thatcontainsorstoresacollec4onofelements

•  Astringisacontainerthatstoresthecollec4onofcharactersinthestring

53 9/21/16

Page 13: Common Loop Algorithms - Westmont Collegedjp3.westmont.edu/.../Lectures/Lecture_10_01.pdfCommon Loop Algorithms 1. Sum and Average Value 2. Coun4ng Matches 3. Promp4ng un4l a Match

while loop -> for loop

stateName="Virginia"i=0whilei<len(stateName):letter=stateName[i]print(letter)i=i+1

whileversion

54 9/21/16

Page 14: Common Loop Algorithms - Westmont Collegedjp3.westmont.edu/.../Lectures/Lecture_10_01.pdfCommon Loop Algorithms 1. Sum and Average Value 2. Coun4ng Matches 3. Promp4ng un4l a Match

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

Page 15: Common Loop Algorithms - Westmont Collegedjp3.westmont.edu/.../Lectures/Lecture_10_01.pdfCommon Loop Algorithms 1. Sum and Average Value 2. Coun4ng Matches 3. Promp4ng un4l a Match

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

Page 16: Common Loop Algorithms - Westmont Collegedjp3.westmont.edu/.../Lectures/Lecture_10_01.pdfCommon Loop Algorithms 1. Sum and Average Value 2. Coun4ng Matches 3. Promp4ng un4l a Match

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

Page 17: Common Loop Algorithms - Westmont Collegedjp3.westmont.edu/.../Lectures/Lecture_10_01.pdfCommon Loop Algorithms 1. Sum and Average Value 2. Coun4ng Matches 3. Promp4ng un4l a Match

Syntax of a for Statement (Container) •  Usingaforlooptoiterateoverthecontentsofacontainer,anelementata4me.

58 9/21/16

Page 18: Common Loop Algorithms - Westmont Collegedjp3.westmont.edu/.../Lectures/Lecture_10_01.pdfCommon Loop Algorithms 1. Sum and Average Value 2. Coun4ng Matches 3. Promp4ng un4l a Match

Syntax of a for Statement (Range) •  Youcanuseaforloopasacount-controlledlooptoiterateoverarangeofintegervalues

•  Weusetherangefunc4onforgenera4ngasequenceofintegersthatlessthantheargumentthatcanbeusedwiththeforloop

59 9/21/16

Page 19: Common Loop Algorithms - Westmont Collegedjp3.westmont.edu/.../Lectures/Lecture_10_01.pdfCommon Loop Algorithms 1. Sum and Average Value 2. Coun4ng Matches 3. Promp4ng un4l a Match

Planning a for Loop •  Printthebalanceattheendofeachyearforanumberofyears

60 9/21/16

Page 20: Common Loop Algorithms - Westmont Collegedjp3.westmont.edu/.../Lectures/Lecture_10_01.pdfCommon Loop Algorithms 1. Sum and Average Value 2. Coun4ng Matches 3. Promp4ng un4l a Match

Good Examples of for Loops •  Keeptheloopssimple!

61 9/21/16

Page 21: Common Loop Algorithms - Westmont Collegedjp3.westmont.edu/.../Lectures/Lecture_10_01.pdfCommon Loop Algorithms 1. Sum and Average Value 2. Coun4ng Matches 3. Promp4ng un4l a Match

Investment Example

62 9/21/16

Page 22: Common Loop Algorithms - Westmont Collegedjp3.westmont.edu/.../Lectures/Lecture_10_01.pdfCommon Loop Algorithms 1. Sum and Average Value 2. Coun4ng Matches 3. Promp4ng un4l a Match

Programming Tip •  Findingthecorrectlowerandupperboundsforaloopcanbeconfusing.•  Shouldyoustartat0orat1?•  Shouldyouuse<=bor<basatermina4oncondi4on?

•  Coun4ngiseasierforloopswithasymmetricbounds.•  Thefollowingloopsareexecutedb-a4mes.

inti=awhilei<b:...i=i+1

foriinrange(a,b):...

63 9/21/16

Page 23: Common Loop Algorithms - Westmont Collegedjp3.westmont.edu/.../Lectures/Lecture_10_01.pdfCommon Loop Algorithms 1. Sum and Average Value 2. Coun4ng Matches 3. Promp4ng un4l a Match

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

Page 24: Common Loop Algorithms - Westmont Collegedjp3.westmont.edu/.../Lectures/Lecture_10_01.pdfCommon Loop Algorithms 1. Sum and Average Value 2. Coun4ng Matches 3. Promp4ng un4l a Match

Summary of the for Loop •  forloopsareverypowerful•  Theforloopcanbeusedtoiterateoverthecontentsofanycontainer,whichisanobjectthatcontainsorstoresacollec4onofelements•  astringisacontainerthatstoresthecollec4onofcharactersinthestring.

•  Aforloopcanalsobeusedasacount-controlledloopthatiteratesoverarangeofintegervalues.

65 9/21/16

Page 25: Common Loop Algorithms - Westmont Collegedjp3.westmont.edu/.../Lectures/Lecture_10_01.pdfCommon Loop Algorithms 1. Sum and Average Value 2. Coun4ng Matches 3. Promp4ng un4l a Match

Steps to Writing a Loop •  Planning:

•  Decidewhatworktodoinsidetheloop•  Specifytheloopcondi4on•  Determinelooptype•  Setupvariablesbeforethefirstloop•  Processresultswhentheloopisfinished•  Tracetheloopwithtypicalexamples

•  Coding:•  ImplementtheloopinPython

66 9/21/16

Page 26: Common Loop Algorithms - Westmont Collegedjp3.westmont.edu/.../Lectures/Lecture_10_01.pdfCommon Loop Algorithms 1. Sum and Average Value 2. Coun4ng Matches 3. Promp4ng un4l a Match

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

Page 27: Common Loop Algorithms - Westmont Collegedjp3.westmont.edu/.../Lectures/Lecture_10_01.pdfCommon Loop Algorithms 1. Sum and Average Value 2. Coun4ng Matches 3. Promp4ng un4l a Match

Nested Loops

9/21/16 68

Page 28: Common Loop Algorithms - Westmont Collegedjp3.westmont.edu/.../Lectures/Lecture_10_01.pdfCommon Loop Algorithms 1. Sum and Average Value 2. Coun4ng Matches 3. Promp4ng un4l a Match

Loops Inside of Loops •  InChapterThreewelearnedhowtonestifstatementstoallowustomakecomplexdecisions•  Rememberthattonesttheifstatementsweneedtoindentthecodeblock

•  Complexproblemssome4mesrequireanestedloop,oneloopnestedinsideanotherloop•  Thenestedloopwillbeindentedinsidethecodeblockofthefirstloop

•  Agoodexampleofusingnestedloopsiswhenyouareprocessingcellsinatable•  Theouterloopiteratesoveralloftherowsinthetable•  Theinnerloopprocessesthecolumnsinthecurrentrow

9/21/16 69

Page 29: Common Loop Algorithms - Westmont Collegedjp3.westmont.edu/.../Lectures/Lecture_10_01.pdfCommon Loop Algorithms 1. Sum and Average Value 2. Coun4ng Matches 3. Promp4ng un4l a Match

Our Example Problem Statement •  PrintaTableHeaderthatcontainsx1,x2,x3,andx4•  PrintaTablewithfourcolumnsandtenrowsthatcontainthepowersofx1,x2,x3,andx4forx=1to10

9/21/16 70

Page 30: Common Loop Algorithms - Westmont Collegedjp3.westmont.edu/.../Lectures/Lecture_10_01.pdfCommon Loop Algorithms 1. Sum and Average Value 2. Coun4ng Matches 3. Promp4ng un4l a Match

Applying Nested Loops •  Howwouldyouprintatablewithrowsandcolumns?

•  Printtopline(header)•  Useaforloop

•  Printtablebody…•  Howmanyrowsareinthetable?•  Howmanycolumnsinthetable?

•  Loopperrow•  Looppercolumn

•  Inourexamplethereare:•  Fourcolumnsinthetable•  Tenrowsinthetable

9/21/16 71

Page 31: Common Loop Algorithms - Westmont Collegedjp3.westmont.edu/.../Lectures/Lecture_10_01.pdfCommon Loop Algorithms 1. Sum and Average Value 2. Coun4ng Matches 3. Promp4ng un4l a Match

Pseudocode to Print the Table Printthetableheader

forxfrom1to10printanewtablerowprintanewline

•  Howdoweprintatablerow?

Fornfrom1to4printxn

•  Wehavetoplacethisloopinsidetheprecedingloop•  Theinnerloopis“nested”insidetheouterloop

9/21/16 72

Page 32: Common Loop Algorithms - Westmont Collegedjp3.westmont.edu/.../Lectures/Lecture_10_01.pdfCommon Loop Algorithms 1. Sum and Average Value 2. Coun4ng Matches 3. Promp4ng un4l a Match

Pseudocode to Print the Table Printthetableheader:

forxfrom1to10fornfrom1to4printXn

printanewline

9/21/16 73

n !

x!

Page 33: Common Loop Algorithms - Westmont Collegedjp3.westmont.edu/.../Lectures/Lecture_10_01.pdfCommon Loop Algorithms 1. Sum and Average Value 2. Coun4ng Matches 3. Promp4ng un4l a Match

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

Page 34: Common Loop Algorithms - Westmont Collegedjp3.westmont.edu/.../Lectures/Lecture_10_01.pdfCommon Loop Algorithms 1. Sum and Average Value 2. Coun4ng Matches 3. Promp4ng un4l a Match

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

Page 35: Common Loop Algorithms - Westmont Collegedjp3.westmont.edu/.../Lectures/Lecture_10_01.pdfCommon Loop Algorithms 1. Sum and Average Value 2. Coun4ng Matches 3. Promp4ng un4l a Match

The Results

9/21/16 76

Page 36: Common Loop Algorithms - Westmont Collegedjp3.westmont.edu/.../Lectures/Lecture_10_01.pdfCommon Loop Algorithms 1. Sum and Average Value 2. Coun4ng Matches 3. Promp4ng un4l a Match

First Exercise •  Opentheprogram:

•  powertable.py

•  Runtheprogramandreviewtheresults

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

9/21/16 77

Page 37: Common Loop Algorithms - Westmont Collegedjp3.westmont.edu/.../Lectures/Lecture_10_01.pdfCommon Loop Algorithms 1. Sum and Average Value 2. Coun4ng Matches 3. Promp4ng un4l a Match

Nested Loop Examples

9/21/16 78

Page 38: Common Loop Algorithms - Westmont Collegedjp3.westmont.edu/.../Lectures/Lecture_10_01.pdfCommon Loop Algorithms 1. Sum and Average Value 2. Coun4ng Matches 3. Promp4ng un4l a Match

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

Page 39: Common Loop Algorithms - Westmont Collegedjp3.westmont.edu/.../Lectures/Lecture_10_01.pdfCommon Loop Algorithms 1. Sum and Average Value 2. Coun4ng Matches 3. Promp4ng un4l a Match

Nested Loop Examples (2)

9/21/16 80

Page 40: Common Loop Algorithms - Westmont Collegedjp3.westmont.edu/.../Lectures/Lecture_10_01.pdfCommon Loop Algorithms 1. Sum and Average Value 2. Coun4ng Matches 3. Promp4ng un4l a Match

Second Problem Statement •  Printthefollowingpapernofbrackets:[][][][][][][][][][][][]

•  Thepapernconsistsof:•  Threerows•  Eachrowhasfourpairsofbrackets

•  Whatdoweknow?•  Weneedtwonestedloops

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

9/21/16 81

Page 41: Common Loop Algorithms - Westmont Collegedjp3.westmont.edu/.../Lectures/Lecture_10_01.pdfCommon Loop Algorithms 1. Sum and Average Value 2. Coun4ng Matches 3. Promp4ng un4l a Match

Pseudocode Code, Results Fori=1to3Forj=1to4Print“[]”

Printanewline

9/21/16 82

Page 42: Common Loop Algorithms - Westmont Collegedjp3.westmont.edu/.../Lectures/Lecture_10_01.pdfCommon Loop Algorithms 1. Sum and Average Value 2. Coun4ng Matches 3. Promp4ng un4l a Match

Exam Averages Problem Statement •  Itiscommontorepeatedlyreadandprocessmul4plegroupsofvalues:

•  Writeaprogramthatcancomputetheaverageexamgradeformul4plestudents.

•  Eachstudenthasthesamenumberofexamgrades•  Prompttheuserforthenumberofexams•  Whenyoufinishastudentprompttheusertoseeiftherearemorestudentstoprocess

•  Whatdoweknow?

•  Whatdoweneedtocompute?

•  Whatisouralgorithm/approach?

9/21/16 83

Page 43: Common Loop Algorithms - Westmont Collegedjp3.westmont.edu/.../Lectures/Lecture_10_01.pdfCommon Loop Algorithms 1. Sum and Average Value 2. Coun4ng Matches 3. Promp4ng un4l a Match

Step One: Understand the Problem •  Tocomputetheaveragegradeforastudent,wemustreadandtallyallofthegradesforthatstudent•  Wecanusealooptodothis.(wehaveworkingcodetodothispor8on)

•  Weneedtocomputegradesformul4plestudents•  ThatimpliesasetofnestedLoops

•  Theouterloopprocesseseachstudent•  Theinnerloopprocessthestudent’sgrades

9/21/16 84

Page 44: Common Loop Algorithms - Westmont Collegedjp3.westmont.edu/.../Lectures/Lecture_10_01.pdfCommon Loop Algorithms 1. Sum and Average Value 2. Coun4ng Matches 3. Promp4ng un4l a Match

Step Two •  Computethegradeforonestudent

•  Setupthevariablesandloop

•  Weknowhowmanygradestoprocess,sowecanuseacount-controlledloop

totalscore=0Foriinrange(1,numberofexams+1):ReadthenextexamscoreAddtheexamscoretothetotalscore

ComputetheexamaveragePrinttheexamaverage

9/21/16 85

Page 45: Common Loop Algorithms - Westmont Collegedjp3.westmont.edu/.../Lectures/Lecture_10_01.pdfCommon Loop Algorithms 1. Sum and Average Value 2. Coun4ng Matches 3. Promp4ng un4l a Match

Step Three •  Repeattheprocessforeachstudent•  Sincewedon’tknowhowmanystudentsthereare,wewilluseawhileloopwithasen4nelvalue•  Forsimplicitywewilluse“Y”asthesen4nelvalue

9/21/16 86

Page 46: Common Loop Algorithms - Westmont Collegedjp3.westmont.edu/.../Lectures/Lecture_10_01.pdfCommon Loop Algorithms 1. Sum and Average Value 2. Coun4ng Matches 3. Promp4ng un4l a Match

Step Four: Translate to Python

9/21/16 87

Page 47: Common Loop Algorithms - Westmont Collegedjp3.westmont.edu/.../Lectures/Lecture_10_01.pdfCommon Loop Algorithms 1. Sum and Average Value 2. Coun4ng Matches 3. Promp4ng un4l a Match

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

Page 48: Common Loop Algorithms - Westmont Collegedjp3.westmont.edu/.../Lectures/Lecture_10_01.pdfCommon Loop Algorithms 1. Sum and Average Value 2. Coun4ng Matches 3. Promp4ng un4l a Match

Turning the Indent Guides On

9/21/16 89

Page 49: Common Loop Algorithms - Westmont Collegedjp3.westmont.edu/.../Lectures/Lecture_10_01.pdfCommon Loop Algorithms 1. Sum and Average Value 2. Coun4ng Matches 3. Promp4ng un4l a Match

Application: Random Numbers and Simulations

9/21/16 90

Page 50: Common Loop Algorithms - Westmont Collegedjp3.westmont.edu/.../Lectures/Lecture_10_01.pdfCommon Loop Algorithms 1. Sum and Average Value 2. Coun4ng Matches 3. Promp4ng un4l a Match

Random Numbers/Simulations •  Gamesojenuserandomnumberstomakethingsinteres4ng

•  RollingDice•  Spinningawheel•  Pickacard

•  Asimula4onusuallyinvolvesloopingthroughasequenceofevents•  Days•  Events

9/21/16 91

Page 51: Common Loop Algorithms - Westmont Collegedjp3.westmont.edu/.../Lectures/Lecture_10_01.pdfCommon Loop Algorithms 1. Sum and Average Value 2. Coun4ng Matches 3. Promp4ng un4l a Match

Generating Random Numbers •  ThePythonlibraryhasarandomnumbergeneratorthatproducesnumbersthatappeartoberandom•  Thenumbersarenotcompletelyrandom.Thenumbersaredrawnfromasequenceofnumbersthatdoesnotrepeatforalong4me

•  random()returnsanumberthatis>=0and<1

9/21/16 92

Page 52: Common Loop Algorithms - Westmont Collegedjp3.westmont.edu/.../Lectures/Lecture_10_01.pdfCommon Loop Algorithms 1. Sum and Average Value 2. Coun4ng Matches 3. Promp4ng un4l a Match

Simulating Die Tosses •  Goal:

•  Togeneratearandomintegerinagivenrangeweusetherandint()func4on

•  Randinthastwoparameters,therange(inclusive)ofnumbersgenerated

9/21/16 93


Recommended