modules in python decision control: conditionals · 2019. 9. 25. · modules in python • we can...

25
Modules in Python Decision Control: Conditionals CS 8: Introduction to Computer Science, Spring 2019 Lecture #5 Ziad Matni, Ph.D. Dept. of Computer Science, UCSB

Upload: others

Post on 23-Sep-2020

18 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Modules in Python Decision Control: Conditionals · 2019. 9. 25. · Modules in Python • We can collect a bunch of Python functions and save them together in a file – Often called

ModulesinPythonDecisionControl:Conditionals

CS8:IntroductiontoComputerScience,Spring2019Lecture#5

ZiadMatni,Ph.D.

Dept.ofComputerScience,UCSB

Page 2: Modules in Python Decision Control: Conditionals · 2019. 9. 25. · Modules in Python • We can collect a bunch of Python functions and save them together in a file – Often called

Administrative•  Hw02–duetoday•  Hw03–duenextweek•  Lab01–dueonSundaybymidnight(11:59pm)onGradescope!

•  YoucancheckoldhomeworkonGradeScope4/16/19 Matni,CS8,Sp19 2

Page 3: Modules in Python Decision Control: Conditionals · 2019. 9. 25. · Modules in Python • We can collect a bunch of Python functions and save them together in a file – Often called

LectureOutline•  print()vs.return

•  ModulesinPython

•  BooleanOperations

•  Conditionalsi.e.DecisionControl4/16/19 Matni,CS8,Sp19 3

Page 4: Modules in Python Decision Control: Conditionals · 2019. 9. 25. · Modules in Python • We can collect a bunch of Python functions and save them together in a file – Often called

Printvs.ReturnWhat’sthedifferencebetweenthese2functions?defreturn_dbl(x):returnx*2

defprint_dbl(x):print(x*2)

4/16/19 Matni,CS8,Sp19 4

WhathappensifIdothisinIDLE?>>>a=13>>>return_dbl(a)>>>print_dbl(a)

WhathappensifIdothisinaprogram?a=13return_dbl(a)print_dbl(a)

Page 5: Modules in Python Decision Control: Conditionals · 2019. 9. 25. · Modules in Python • We can collect a bunch of Python functions and save them together in a file – Often called

Printvs.Returndefreturn_dbl(x):returnx*2

defprint_dbl(x):print(x*2)

4/16/19 Matni,CS8,Sp19 5

WhathappensifIdothisinIDLE?>>>a=13>>>print(return_dbl(a))>>>print(print_dbl(a))

Woulditbedifferentinaprogram?

Printingvs.returningtheoutputcanleadtoverydifferentbehaviors!!!!!

Page 6: Modules in Python Decision Control: Conditionals · 2019. 9. 25. · Modules in Python • We can collect a bunch of Python functions and save them together in a file – Often called

ModulesinPython•  WecancollectabunchofPythonfunctionsandsavethem

togetherinafile–  Oftencalledamoduleorlibrary–  It’sagoodwaytoorganizefunctionsthat“gotogether”foraspecific

purpose–  Themodulecanalsohaveothercoderelatedtothesefunctions

•  Wecanthen“import”thatfileoverandusethefunctionsforourselvesinourownprogramfiles

4/16/19 Matni,CS8,Sp19 6

Page 7: Modules in Python Decision Control: Conditionals · 2019. 9. 25. · Modules in Python • We can collect a bunch of Python functions and save them together in a file – Often called

ModulesinPython•  RecallthatPythonisOpen-SourceSoftware– Whatdoesthatmean?

•  Alotofmoduleshavebeencreatedbyvariouspeopleandthenputupforanyonetouse–  Example:modulestodoadvancedstatisticalanalysis,tohelpsolvelinearalgebraprobs,helpsolveODEs,etc…

–  Google“popularpythonlibraries”!

4/16/19 Matni,CS8,Sp19 7

Page 8: Modules in Python Decision Control: Conditionals · 2019. 9. 25. · Modules in Python • We can collect a bunch of Python functions and save them together in a file – Often called

Reminder:HowCanWeUseFunctions?

•  Oncewedefinethem,wecancallthem:–  Inaprogram(insamefilewherethey’redefined)–  IntheIDLEPythonshell–  Example:MyFunction(5,6,7)

•  Wecanalsocallthem:–  Fromanotherfilealtogether–  (totestthemfrom)usingPytest

4/16/19 Matni,CS8,Sp19 8

Page 9: Modules in Python Decision Control: Conditionals · 2019. 9. 25. · Modules in Python • We can collect a bunch of Python functions and save them together in a file – Often called

CreatingaModuleConsideracoupleoffunctionsthatwewroteandthatwe’dliketouseinotherPythonprograms:

#Doublingfunctiondefdbl(x):return2*x

#Halvingfunctiondefhalf(x):returnx/2

4/16/19 Matni,CS8,Sp19 9

Savetheminafile.Let’scallitPinkFloyd.py(justhappenedtobewhatIwaslisteningto,butI’msureyoucancomeupwithabettername)

Page 10: Modules in Python Decision Control: Conditionals · 2019. 9. 25. · Modules in Python • We can collect a bunch of Python functions and save them together in a file – Often called

UsingModulesinOtherFilesInsideanotherfile,wecanstillusethefunctionswedefinedandsavedinPinkFloyd.py,likethis:#WewanttousethosefunctionsinPinkFloyd.pyimportPinkFloyd#fromPinkFloydimport*#anotherwaytodothisprint("InsidePinkFloyd.py")print(PinkFloyd.dbl(5))print(PinkFloyd.dbl("UCSB"))print(PinkFloyd.dbl([1,2,3]))print(PinkFloyd.half(42))

4/16/19 Matni,CS8,Sp19 10

#Doublingfunctiondefdbl(x):

return2*x#Halvingfunctiondefhalf(x):

returnx/2

InsidePinkFloyd.py

InsideSomeOtherFile.py

Page 11: Modules in Python Decision Control: Conditionals · 2019. 9. 25. · Modules in Python • We can collect a bunch of Python functions and save them together in a file – Often called

ConditionalExecutionWhatifmymodule(e.g.PinkFloyd.py)hasinstructionsinitotherthanthefunctiondefs?#Doublingfunctiondefdbl(x):

return2*x#Halvingfunctiondefhalf(x):

returnx/2print("I'minsidePinkFloyd.py")print(dbl(82.12))

4/16/19 Matni,CS8,Sp19 11

Whenyouimportthemodule,youmayNOTwantthisstufftoexecute

Page 12: Modules in Python Decision Control: Conditionals · 2019. 9. 25. · Modules in Python • We can collect a bunch of Python functions and save them together in a file – Often called

ConditionalExecutionWhatifmymodule(e.g.PinkFloyd.py)hasinstructionsinitotherthanthefunctiondefs?#Doublingfunctiondefdbl(x):

return2*x#Halvingfunctiondefhalf(x):

returnx/2if__name__=="__main__":

print("I'minsidePinkFloyd.py”)print(dbl(82.12))

4/16/19 Matni,CS8,Sp19 12

Addthisconditionalstatement.Nowthe2printstatementsareonlyexecutedwhenwerunPinkFloyd.py,notwhenweimportit

Page 13: Modules in Python Decision Control: Conditionals · 2019. 9. 25. · Modules in Python • We can collect a bunch of Python functions and save them together in a file – Often called

Testing#test_dbl.pyimportpytestfromPinkFloydimportdbldeftest_dbl_1():

assertdbl(0)==0deftest_dbl_2():

assertdbl(2)==4deftest_dbl_3():

assertdbl("UCSB")=="UCSBUCSB"Runthesetestsfromtheunixcommandline:$python3–mpytesttest_dbl.py4/16/19 Matni,CS8,Sp19 13

Page 14: Modules in Python Decision Control: Conditionals · 2019. 9. 25. · Modules in Python • We can collect a bunch of Python functions and save them together in a file – Often called

RelationalOperators•  Tocheckiftwoobjectsareequal,weuse:

==operator•  Wecancheckothertypesofrelationshipsbetweentwoobjects:<<=>>=!=

4/16/19 Matni,CS8,Sp19 14

LessthanLessthanorequaltoGreaterthanGreaterthanorequaltoNotequalto

Q:Alloftheseproducewhatkindofdatatype?A:Boolean(i.e.TrueorFalse)

Page 15: Modules in Python Decision Control: Conditionals · 2019. 9. 25. · Modules in Python • We can collect a bunch of Python functions and save them together in a file – Often called

WhatistheOutputoftheprint()statement?

a=3b=(a!=3)print(b)A.  TrueB.  FalseC.  3D.  Syntaxerror4/16/19 Matni,CS8,Sp19 15

Page 16: Modules in Python Decision Control: Conditionals · 2019. 9. 25. · Modules in Python • We can collect a bunch of Python functions and save them together in a file – Often called

LogicOperators•  LogicAND

–  UseinPython:xandy–  PresentsaTrueoutputifbothxandyareTrue

•  LogicOR–  UseinPython:xory–  PresentsaTrueoutputifeitherxandyareTrue

•  LogicNOT–  UseinPython:notx–  PresentsaTrueoutputifxisFalse(andvice-versa)

4/16/19 Matni,CS8,Sp19 16

Page 17: Modules in Python Decision Control: Conditionals · 2019. 9. 25. · Modules in Python • We can collect a bunch of Python functions and save them together in a file – Often called

Exercise1Whatistheoutputoftheseprint()statements?x=Truey=Falsez=Trueprint(xandy)print(xandnoty)print((xandy)orz)

4/16/19 Matni,CS8,Sp19 17

çFalseçTrue

çTrue

Page 18: Modules in Python Decision Control: Conditionals · 2019. 9. 25. · Modules in Python • We can collect a bunch of Python functions and save them together in a file – Often called

Exercise2Whatistheoutputoftheseprint()statements?a=3b=4c=5print(a==3andb==4)print(not(b<2)andnot(a!=5))print((a>0orb==0)and(c<=5))

4/16/19 Matni,CS8,Sp19 18

çTrueçFalse

çTrue

Page 19: Modules in Python Decision Control: Conditionals · 2019. 9. 25. · Modules in Python • We can collect a bunch of Python functions and save them together in a file – Often called

ControllingtheFlowofaProgram•  Programswilloftenneedtomakedecisionsonwhattocontinuedoing–  Likecomingtoaforkintheroad…

•  Wepresentthealgorithm/programwith aconditionalstatement(a.k.aif-then-else)

4/16/19 Matni,CS8,Sp19 20

Page 20: Modules in Python Decision Control: Conditionals · 2019. 9. 25. · Modules in Python • We can collect a bunch of Python functions and save them together in a file – Often called

ConditionalStatements:ifandelse

4/16/19 Matni,CS8,Sp19 21

Let’s try it out!

TypicalExample(NOTETHEINDENTS!!!)x=int(input("Enteranyinteger:"))ifx>=0:

print("Youenteredapositivenumber!")print("Oritcouldbezero!")

else:print("Youenteredanegativenumber!")

Page 21: Modules in Python Decision Control: Conditionals · 2019. 9. 25. · Modules in Python • We can collect a bunch of Python functions and save them together in a file – Often called

ConditionalStatements:ifandelseThesyntaxinPythonis:

if conditional_statement : statement 1 statement 2 …

elif conditional_statement : else statements

elif conditional_statement : more else statements

else: default else statements

4/16/19 Matni,CS8,Sp19 22

Let’s try it out!

a=int(input("Enteranumber:"))#Theabovelinemakestheprogram#asktheuserforadirectinput#intoaninteger.Moreonthislater.if(a<5):

print("It’slessthanfive!")elif(a>5):

print("It’smorethanfive!!!")else:

print("It’sequaltofive!!!!!")

Page 22: Modules in Python Decision Control: Conditionals · 2019. 9. 25. · Modules in Python • We can collect a bunch of Python functions and save them together in a file – Often called

ConditionalStatementsAREBooleanValues

4/16/19 Matni,CS8,Sp19 23

a=int(input("Enteranumber:"))#Theabovelinemakestheprogram#asktheuserforadirectinput#intoaninteger.Moreonthislater.if(a<5):

print("It’slessthanfive!")elif(a>5):

print("It’smorethanfive!!!")else:

print("It’sequaltofive!!!!!")

Booleanstatements(they’reeitherTRUEorFALSE)

Page 23: Modules in Python Decision Control: Conditionals · 2019. 9. 25. · Modules in Python • We can collect a bunch of Python functions and save them together in a file – Often called

NestedIf-ElseStatements

4/16/19 Matni,CS8,Sp19 24

Let’s try it out!

a=int(input("WhatisthecostofitemX?"))b=int(input("Enter(0)fornotavailable,(1)foravailable"))if(b==0):

print("Itdoesn’tmatterwhatitcosts:it’snotavailable!")else:

if(a>=100): print("That’sexpensive!")else: print("That’snottooexpensive!")

Think of If-Else as a way to describe “logical branching” Whatdoesthisdo?

Exercise:WhathappensifIenter:1.  100foraand0forb?2.  200foraand1forb?3.  20foraand0forb?4.  99foraand1forb?

Page 24: Modules in Python Decision Control: Conditionals · 2019. 9. 25. · Modules in Python • We can collect a bunch of Python functions and save them together in a file – Often called

YOURTO-DOsq  FinishreadingChapter3q  StartreadingChapter5q  StartonHW3(duenextTUESDAY)q  DoLab1(turnitinbySunday)

q  Dancelikeyoumeanit4/16/19 Matni,CS8,Sp19 25

Page 25: Modules in Python Decision Control: Conditionals · 2019. 9. 25. · Modules in Python • We can collect a bunch of Python functions and save them together in a file – Often called

4/16/19 Matni,CS8,Sp19 26