Loops ISYS 350. Three Types of Loops while loop do while loop for loop.
Loops in Python - GitHub PagesRepetition with a while loop • while condition: # executes over and...
Transcript of Loops in Python - GitHub PagesRepetition with a while loop • while condition: # executes over and...
LoopsinPython
CS8:IntroductiontoComputerScience,Winter2019Lecture#7
ZiadMatni,Ph.D.
Dept.ofComputerScience,UCSB
Administrative• Myofficehours:rescheduledtoday:
2:30pm–3:30pm(justfortoday…)
• Hw04–duenextweekonMONDAYinclass• Lab03–duenextweekonMONDAYbymidnight
• YoucancheckoldhomeworkonGradeScope
• MidtermExam#1isnextWednesday!!!– StudyGuidewillbeONOURWEBSITEbytomorrow
1/29/19 Matni,CS8,Wi19 2
Midterm#1Exam• Feb.6th9:30AM–10:45AM• InTHISclassroom(unlessyouareaDSPstudent)• Come10MINUTESEARLYasthereispre-assignedseating• CLOSEDBOOK!Butyoucanbring1pageofnotes
– Single-sideonly,8.5”x11”– Hand-writtenorcomputerprintedisOK!– Mustturnitinwiththeexamwhendone– Nocalculators/cellphones/anytypeofcomputer
• BringyourUCSBIDwithyou.NOEXCEPTIONS.1/29/19 Matni,CS8,Wi19 3
Midterm#1ExamWHAT’SONIT?!
• Everything– ReviewALLlectures– ReviewALLreadings– ReviewALLlabs– ReviewALLhomework
1/29/19 Matni,CS8,Wi19 4
Midterm#1ExamSAMPLEQUESTIONS?!?!?!?!?!?!
• Yes!SeeStudyGuideontheclasswebsite!
1/29/19 Matni,CS8,Wi19 5
LectureOutline• Loops
1/29/19 Matni,CS8,Wi19 6
ClassExerciseGettogetherwith2or3otherpeoplearoundyouandanswerthisquestion.
Youcanuseyournotesfromlasttime.Youcanuseyourcomputers:
a)WriteashortPythoncodethatasksausertheirage.Onceyoudothat,decidewhethertoprintout“Yourageisanevennumber!”or“Yourageisanoddnumber!”dependingontheiranswer.b)Nowmodifyyourcodesothatitcandetectifsomeoneenteredanumberlessthan1astheirage.Ifso,printoutarejectionmessageandquit.Challenge:dothistwice:oncebyusingtheandoperatorandoncewithoutusingand(usingnested-ifstatements)
1/29/19 Matni,CS8,Wi19 7
ClassExerciseage=int(input("Howoldareyou?"))if(age%2==0):
print("Yourageisanevennumber!")else:
print("Yourageisanoddnumber!")
1/29/19 Matni,CS8,Wi19 8
ClassExerciseage=int(input("Howoldareyou?"))if(age%2==0)and(age>0):
print("Yourageisanevennumber!")elif(age%2!=0)and(age>0):
print("Yourageisanoddnumber!")else:
print("Youhaveenteredanillegalage!")
1/29/19 Matni,CS8,Wi19 9
ClassExerciseage=int(input("Howoldareyou?"))if(age>0):
if(age%2==0): print("Yourageisanevennumber!")else: print("Yourageisanoddnumber!")
else:print("Youhaveenteredanillegalage!")
1/29/19 Matni,CS8,Wi19 10
Loops• Sometimeswewanttobeabletorepeatapartoftheprograma
certainnumberoftimeswithoutbeingrepetitive– Calleda“loop”
• Soinsteadofsaying: print(“hello”) print(“hello”) print(“hello”)
Icansay: dothefollowing3times: print(“hello”)
• Apopularwaytodothisiswith theforandthewhile commands.
1/29/19 Matni,CS8,Wi19 11
Repetitionwithaforloop• for refin somelist: #blockofinstructions–refreferstocurrentobjectinlist #notethattheblockisallindented– for,in,:–mandatoryparts– ref–anameforreferringtoobjectsinthelist
• Example:fornumbersin(0,1,2,3,4,5): print(numbers)
Thiswillprintoutthenumbers1thru5insequence
1/29/19 Matni,CS8,Wi19 12
OtherExamplesforxin(9,22,-77,1):
y=x+10print(y)
foryin("Hello","Mother","Hello","Father"):
print(x,"!!")n=0foritemin["UCSBLocation",(34.4140,-119.8489)]:
n=n+1print(n,item)
1/29/19 Matni,CS8,Wi19 13
WHATDOYOUTHINKTHESELOOPSPRINTOUT?
Usingrangewithforloops• Therange()built-infunctionprovidesahandylist• Simplestuse:range(n)
– Createsalistwithnitems[0, 1, 2, …n-1]
• Example: fornumbersinrange(6): print(numbers)
Thiswillprintoutthenumbers1thru5insequence
(justlikethelastexample)
1/29/19 Matni,CS8,Wi19 14
OtherExamplesforxinrange(7):
print(x)foryinrange(2,9):
print(x-2)foriteminrange(5,-1,-1):
ifitem==0: print(item,"Blastoff!!")else: print(item)
1/29/19 Matni,CS8,Wi19 15
WHATDOYOUTHINKTHESELOOPSPRINTOUT?
Repetitionwithawhileloop• while condition: #executesoverandoveruntilaconditionisFalse
• Usedforindefiniteiteration
– Whenitisn’tpossibletopredicthowmanytimesaloopneedstoexecute,unlikewithforloops
• Weuseforloopsfordefiniteiteration (e.g.,theloopexecutesexactlyntimes)
1/29/19 Matni,CS8,Wi19 16
Repetitionwithawhileloop• while condition: #executesoverandoveruntilaconditionisFalse
• Whileloopswon’trunatallifconditionstartsoutasfalse
• Whileloopsrunforeverifconditionneverbecomesfalse(i.e.ifitalwaysstaystrue)
• Socaremustdoneindesigningthesesortofloops.
1/29/19 Matni,CS8,Wi19 17
Applyingwhile Canbeusedforcounter-controlledloops:
n=500counter=0#(1)initializewhilecounter<n:#(2)checkconditionprint(counter*counter)counter=counter+1#(3)changestate
– ButNOTEthatthisisadefiniteloop–easiertouseaforloop:forcounterinrange(500): …etc…
1/29/19 Matni,CS8,Wi19 18
ApplyingwhileThisisabetterapplicationexample–unlimiteddataentry:
AllGrades=0 #(1)initializegrade=int(input("entergradeorqtoquit:"))whilegrade!="q": #(2)checkcondition AllGrades=AllGrades+grades #processgrade grade=int(input("entergradeorqtoquit:"))#askagain
#Whileloophasended(noindentsafterhere),#nowyoucandootherstuff…print("Totalgradesis:",AllGrades)print("You'realldonenow!")
1/29/19 Matni,CS8,Wi19 19
YOURTO-DOsq FinishreadingChapter5
q We’llbediscussingloopsonWednesday
q StartonHW4(duenextMONDAY)q DoLab3(labtomorrow;turnitinbyFriday)
q Don’tbikeangry!1/29/19 Matni,CS8,Wi19 20
1/29/19 Matni,CS8,Wi19 21