modules in python decision control - github pagesmodules in python • we can collect a bunch of...
TRANSCRIPT
ModulesinPythonDecisionControl
CS8:IntroductiontoComputerScience,Winter2019Lecture#6
ZiadMatni,Ph.D.
Dept.ofComputerScience,UCSB
Administrative• Hw03–duetoday!• Hw04–duenextweekonMONDAY
• YoucancheckoldhomeworkonGradeScope
• Lab03onTuesday– Extendedduedate!DuebynextweekMonday!
• MidtermExam#1isonWed.Feb.6th1/27/19 Matni,CS8,Wi19 2
ANoteonHomeworkExpectations• Yourlecturenotes• Mylectureslides• Thebookchaptersections• Your“detective”work– i.e.trythingsoutonIDLE
• Practice,Practice,Practice!!!1/25/19 Matni,CS8,Wi19 3
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/27/19 Matni,CS8,Wi19 4
LectureOutline• ModulesinPython
• BooleanOperations
• Conditionalsi.e.DecisionControl
1/25/19 Matni,CS8,Wi19 5
ModulesinPython• WecancollectabunchofPythonfunctionsandsavethem
togetherinafile– Oftencalledamoduleorlibrary– It’sagoodwaytoorganizefunctionsthat“gotogether”foraspecific
purpose– Themodulecanalsohaveothercoderelatedtothesefunctions
• Wecanthen“import”thatfileoverandusethefunctionsforourselvesinourownprogramfiles
1/25/19 Matni,CS8,Wi19 6
ModulesinPython• RecallthatPythonisOpen-SourceSoftware– Whatdoesthatmean?
• Alotofmoduleshavebeencreatedbyvariouspeopleandthenputupforanyonetouse– Example:modulestodoadvancedstatisticalanalysis,tohelpsolvelinearalgebraprobs,helpsolveODEs,etc…
– Google“popularpythonlibraries”!
1/27/19 Matni,CS8,Wi19 7
Reminder:HowCanWeUseFunctions?
• Oncewedefinethem,wecancallthem:– Inaprogram(insamefilewherethey’redefined)– IntheIDLEPythonshell– Example:MyFunction(5,6,7)
• Wecanalsocallthem:– Fromanotherfilealtogether– (totestthemfrom)usingPytest
1/26/19 Matni,CS8,Wi19 8
CreatingaModuleConsideracoupleoffunctionsthatwewroteandthatwe’dliketouseinotherPythonprograms:
#Doublingfunctiondefdbl(x):return2*x
#Halvingfunctiondefhalf(x):returnx/2
1/25/19 Matni,CS8,Wi19 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))
1/26/19 Matni,CS8,Wi19 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))
1/26/19 Matni,CS8,Wi19 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))
1/26/19 Matni,CS8,Wi19 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.py1/26/19 Matni,CS8,Wi19 13
RelationalOperators• Tocheckiftwoobjectsareequal,weuse:
==operator• Wecancheckothertypesofrelationshipsbetweentwoobjects:<<=>>=!=
1/26/19 Matni,CS8,Wi19 14
LessthanLessthanorequaltoGreaterthanGreaterthanorequaltoNotequalto
Q:Alloftheseproducewhatkindofdatatype?A:Boolean(i.e.TrueorFalse)
WhatistheOutputoftheprint()statement?
a=3b=(a!=3)print(b)A. TrueB. FalseC. 3D. Syntaxerror1/26/19 Matni,CS8,Wi19 15
LogicOperators• LogicAND
– UseinPython:xandy– PresentsaTrueoutputifbothxandyareTrue
• LogicOR– UseinPython:xory– PresentsaTrueoutputifeitherxandyareTrue
• LogicNOT– UseinPython:notx– PresentsaTrueoutputifxisFalse(andvice-versa)
1/26/19 Matni,CS8,Wi19 16
Exercise1Whatistheoutputoftheseprint()statements?x=Truey=Falsez=Trueprint(xandy)print(xandnoty)print((xandy)orz)
1/26/19 Matni,CS8,Wi19 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))
1/26/19 Matni,CS8,Wi19 18
çTrueçFalse
çTrue
Exercise3• Writeafunction,CheckNegInt()thattakesinoneargumentxandreturnsTrueif2conditionsaremet:– Thatxisaninteger– Thatxisanegativenumber
defCheckNegInt(x):c=Falseif(type(x)==int)and(x<0): c=Truereturnc
1/26/19 Matni,CS8,Wi19 19
ControllingtheFlowofaProgram• Programswilloftenneedtomakedecisionsonwhattocontinuedoing– Likecomingtoaforkintheroad…
• Wepresentthealgorithm/programwith aconditionalstatement(a.k.aif-then-else)
1/27/19 Matni,CS8,Wi19 20
ConditionalStatements:ifandelse
1/27/19 Matni,CS8,Wi19 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
1/28/19 Matni,CS8,Wi19 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
1/27/19 Matni,CS8,Wi19 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
1/27/19 Matni,CS8,Wi19 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 FinishreadingChapter5
q We’llbediscussingloopsonWednesday
q StartonHW4(duenextMONDAY)q DoLab3(labtomorrow;turnitinbyFriday)
q Don’tbikeangry!1/25/19 Matni,CS8,Wi19 25
1/25/19 Matni,CS8,Wi19 26