modules in python decision control: conditionals · 2019. 9. 25. · modules in python • we can...
TRANSCRIPT
ModulesinPythonDecisionControl:Conditionals
CS8:IntroductiontoComputerScience,Spring2019Lecture#5
ZiadMatni,Ph.D.
Dept.ofComputerScience,UCSB
Administrative• Hw02–duetoday• Hw03–duenextweek• Lab01–dueonSundaybymidnight(11:59pm)onGradescope!
• YoucancheckoldhomeworkonGradeScope4/16/19 Matni,CS8,Sp19 2
LectureOutline• print()vs.return
• ModulesinPython
• BooleanOperations
• Conditionalsi.e.DecisionControl4/16/19 Matni,CS8,Sp19 3
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)
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!!!!!
ModulesinPython• WecancollectabunchofPythonfunctionsandsavethem
togetherinafile– Oftencalledamoduleorlibrary– It’sagoodwaytoorganizefunctionsthat“gotogether”foraspecific
purpose– Themodulecanalsohaveothercoderelatedtothesefunctions
• Wecanthen“import”thatfileoverandusethefunctionsforourselvesinourownprogramfiles
4/16/19 Matni,CS8,Sp19 6
ModulesinPython• RecallthatPythonisOpen-SourceSoftware– Whatdoesthatmean?
• Alotofmoduleshavebeencreatedbyvariouspeopleandthenputupforanyonetouse– Example:modulestodoadvancedstatisticalanalysis,tohelpsolvelinearalgebraprobs,helpsolveODEs,etc…
– Google“popularpythonlibraries”!
4/16/19 Matni,CS8,Sp19 7
Reminder:HowCanWeUseFunctions?
• Oncewedefinethem,wecancallthem:– Inaprogram(insamefilewherethey’redefined)– IntheIDLEPythonshell– Example:MyFunction(5,6,7)
• Wecanalsocallthem:– Fromanotherfilealtogether– (totestthemfrom)usingPytest
4/16/19 Matni,CS8,Sp19 8
CreatingaModuleConsideracoupleoffunctionsthatwewroteandthatwe’dliketouseinotherPythonprograms:
#Doublingfunctiondefdbl(x):return2*x
#Halvingfunctiondefhalf(x):returnx/2
4/16/19 Matni,CS8,Sp19 9
Savetheminafile.Let’scallitPinkFloyd.py(justhappenedtobewhatIwaslisteningto,butI’msureyoucancomeupwithabettername)
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
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
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
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
RelationalOperators• Tocheckiftwoobjectsareequal,weuse:
==operator• Wecancheckothertypesofrelationshipsbetweentwoobjects:<<=>>=!=
4/16/19 Matni,CS8,Sp19 14
LessthanLessthanorequaltoGreaterthanGreaterthanorequaltoNotequalto
Q:Alloftheseproducewhatkindofdatatype?A:Boolean(i.e.TrueorFalse)
WhatistheOutputoftheprint()statement?
a=3b=(a!=3)print(b)A. TrueB. FalseC. 3D. Syntaxerror4/16/19 Matni,CS8,Sp19 15
LogicOperators• LogicAND
– UseinPython:xandy– PresentsaTrueoutputifbothxandyareTrue
• LogicOR– UseinPython:xory– PresentsaTrueoutputifeitherxandyareTrue
• LogicNOT– UseinPython:notx– PresentsaTrueoutputifxisFalse(andvice-versa)
4/16/19 Matni,CS8,Sp19 16
Exercise1Whatistheoutputoftheseprint()statements?x=Truey=Falsez=Trueprint(xandy)print(xandnoty)print((xandy)orz)
4/16/19 Matni,CS8,Sp19 17
çFalseçTrue
çTrue
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
ControllingtheFlowofaProgram• Programswilloftenneedtomakedecisionsonwhattocontinuedoing– Likecomingtoaforkintheroad…
• Wepresentthealgorithm/programwith aconditionalstatement(a.k.aif-then-else)
4/16/19 Matni,CS8,Sp19 20
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!")
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!!!!!")
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)
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?
YOURTO-DOsq FinishreadingChapter3q StartreadingChapter5q StartonHW3(duenextTUESDAY)q DoLab1(turnitinbySunday)
q Dancelikeyoumeanit4/16/19 Matni,CS8,Sp19 25
4/16/19 Matni,CS8,Sp19 26