Loops in Python - GitHub PagesRepetition with a while loop • while condition: # executes over and...

21
Loops in Python CS 8: Introduction to Computer Science, Winter 2019 Lecture #7 Ziad Matni, Ph.D. Dept. of Computer Science, UCSB

Transcript of Loops in Python - GitHub PagesRepetition with a while loop • while condition: # executes over and...

Page 1: Loops in Python - GitHub PagesRepetition with a while loop • while condition: # executes over and over until a condition is False • While loops won’t run at all if condition

LoopsinPython

CS8:IntroductiontoComputerScience,Winter2019Lecture#7

ZiadMatni,Ph.D.

Dept.ofComputerScience,UCSB

Page 2: Loops in Python - GitHub PagesRepetition with a while loop • while condition: # executes over and over until a condition is False • While loops won’t run at all if condition

Administrative•  Myofficehours:rescheduledtoday:

2:30pm–3:30pm(justfortoday…)

•  Hw04–duenextweekonMONDAYinclass•  Lab03–duenextweekonMONDAYbymidnight

•  YoucancheckoldhomeworkonGradeScope

•  MidtermExam#1isnextWednesday!!!–  StudyGuidewillbeONOURWEBSITEbytomorrow

1/29/19 Matni,CS8,Wi19 2

Page 3: Loops in Python - GitHub PagesRepetition with a while loop • while condition: # executes over and over until a condition is False • While loops won’t run at all if condition

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

Page 4: Loops in Python - GitHub PagesRepetition with a while loop • while condition: # executes over and over until a condition is False • While loops won’t run at all if condition

Midterm#1ExamWHAT’SONIT?!

•  Everything–  ReviewALLlectures–  ReviewALLreadings–  ReviewALLlabs–  ReviewALLhomework

1/29/19 Matni,CS8,Wi19 4

Page 5: Loops in Python - GitHub PagesRepetition with a while loop • while condition: # executes over and over until a condition is False • While loops won’t run at all if condition

Midterm#1ExamSAMPLEQUESTIONS?!?!?!?!?!?!

•  Yes!SeeStudyGuideontheclasswebsite!

1/29/19 Matni,CS8,Wi19 5

Page 6: Loops in Python - GitHub PagesRepetition with a while loop • while condition: # executes over and over until a condition is False • While loops won’t run at all if condition

LectureOutline•  Loops

1/29/19 Matni,CS8,Wi19 6

Page 7: Loops in Python - GitHub PagesRepetition with a while loop • while condition: # executes over and over until a condition is False • While loops won’t run at all if condition

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

Page 8: Loops in Python - GitHub PagesRepetition with a while loop • while condition: # executes over and over until a condition is False • While loops won’t run at all if condition

ClassExerciseage=int(input("Howoldareyou?"))if(age%2==0):

print("Yourageisanevennumber!")else:

print("Yourageisanoddnumber!")

1/29/19 Matni,CS8,Wi19 8

Page 9: Loops in Python - GitHub PagesRepetition with a while loop • while condition: # executes over and over until a condition is False • While loops won’t run at all if condition

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

Page 10: Loops in Python - GitHub PagesRepetition with a while loop • while condition: # executes over and over until a condition is False • While loops won’t run at all if condition

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

Page 11: Loops in Python - GitHub PagesRepetition with a while loop • while condition: # executes over and over until a condition is False • While loops won’t run at all if condition

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

Page 12: Loops in Python - GitHub PagesRepetition with a while loop • while condition: # executes over and over until a condition is False • While loops won’t run at all if condition

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

Page 13: Loops in Python - GitHub PagesRepetition with a while loop • while condition: # executes over and over until a condition is False • While loops won’t run at all if condition

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?

Page 14: Loops in Python - GitHub PagesRepetition with a while loop • while condition: # executes over and over until a condition is False • While loops won’t run at all if condition

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

Page 15: Loops in Python - GitHub PagesRepetition with a while loop • while condition: # executes over and over until a condition is False • While loops won’t run at all if condition

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?

Page 16: Loops in Python - GitHub PagesRepetition with a while loop • while condition: # executes over and over until a condition is False • While loops won’t run at all if condition

Repetitionwithawhileloop•  while condition: #executesoverandoveruntilaconditionisFalse

•  Usedforindefiniteiteration

–  Whenitisn’tpossibletopredicthowmanytimesaloopneedstoexecute,unlikewithforloops

•  Weuseforloopsfordefiniteiteration (e.g.,theloopexecutesexactlyntimes)

1/29/19 Matni,CS8,Wi19 16

Page 17: Loops in Python - GitHub PagesRepetition with a while loop • while condition: # executes over and over until a condition is False • While loops won’t run at all if condition

Repetitionwithawhileloop•  while condition: #executesoverandoveruntilaconditionisFalse

•  Whileloopswon’trunatallifconditionstartsoutasfalse

•  Whileloopsrunforeverifconditionneverbecomesfalse(i.e.ifitalwaysstaystrue)

•  Socaremustdoneindesigningthesesortofloops.

1/29/19 Matni,CS8,Wi19 17

Page 18: Loops in Python - GitHub PagesRepetition with a while loop • while condition: # executes over and over until a condition is False • While loops won’t run at all if condition

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

Page 19: Loops in Python - GitHub PagesRepetition with a while loop • while condition: # executes over and over until a condition is False • While loops won’t run at all if condition

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

Page 20: Loops in Python - GitHub PagesRepetition with a while loop • while condition: # executes over and over until a condition is False • While loops won’t run at all if condition

YOURTO-DOsq  FinishreadingChapter5

q  We’llbediscussingloopsonWednesday

q  StartonHW4(duenextMONDAY)q  DoLab3(labtomorrow;turnitinbyFriday)

q  Don’tbikeangry!1/29/19 Matni,CS8,Wi19 20

Page 21: Loops in Python - GitHub PagesRepetition with a while loop • while condition: # executes over and over until a condition is False • While loops won’t run at all if condition

1/29/19 Matni,CS8,Wi19 21