modules in python decision control - github pagesmodules in python • we can collect a bunch of...

26
Modules in Python Decision Control CS 8: Introduction to Computer Science, Winter 2019 Lecture #6 Ziad Matni, Ph.D. Dept. of Computer Science, UCSB

Upload: others

Post on 09-Jul-2020

30 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Modules in Python Decision Control - GitHub PagesModules in Python • We can collect a bunch of Python functions and save them together in a file – Often called a module or library

ModulesinPythonDecisionControl

CS8:IntroductiontoComputerScience,Winter2019Lecture#6

ZiadMatni,Ph.D.

Dept.ofComputerScience,UCSB

Page 2: Modules in Python Decision Control - GitHub PagesModules in Python • We can collect a bunch of Python functions and save them together in a file – Often called a module or library

Administrative•  Hw03–duetoday!•  Hw04–duenextweekonMONDAY

•  YoucancheckoldhomeworkonGradeScope

•  Lab03onTuesday–  Extendedduedate!DuebynextweekMonday!

•  MidtermExam#1isonWed.Feb.6th1/27/19 Matni,CS8,Wi19 2

Page 3: Modules in Python Decision Control - GitHub PagesModules in Python • We can collect a bunch of Python functions and save them together in a file – Often called a module or library

ANoteonHomeworkExpectations•  Yourlecturenotes•  Mylectureslides•  Thebookchaptersections•  Your“detective”work–  i.e.trythingsoutonIDLE

•  Practice,Practice,Practice!!!1/25/19 Matni,CS8,Wi19 3

Page 4: Modules in Python Decision Control - GitHub PagesModules in Python • We can collect a bunch of Python functions and save them together in a file – Often called a module or library

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

Page 5: Modules in Python Decision Control - GitHub PagesModules in Python • We can collect a bunch of Python functions and save them together in a file – Often called a module or library

LectureOutline•  ModulesinPython

•  BooleanOperations

•  Conditionalsi.e.DecisionControl

1/25/19 Matni,CS8,Wi19 5

Page 6: Modules in Python Decision Control - GitHub PagesModules in Python • We can collect a bunch of Python functions and save them together in a file – Often called a module or library

ModulesinPython•  WecancollectabunchofPythonfunctionsandsavethem

togetherinafile–  Oftencalledamoduleorlibrary–  It’sagoodwaytoorganizefunctionsthat“gotogether”foraspecific

purpose–  Themodulecanalsohaveothercoderelatedtothesefunctions

•  Wecanthen“import”thatfileoverandusethefunctionsforourselvesinourownprogramfiles

1/25/19 Matni,CS8,Wi19 6

Page 7: Modules in Python Decision Control - GitHub PagesModules in Python • We can collect a bunch of Python functions and save them together in a file – Often called a module or library

ModulesinPython•  RecallthatPythonisOpen-SourceSoftware– Whatdoesthatmean?

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

–  Google“popularpythonlibraries”!

1/27/19 Matni,CS8,Wi19 7

Page 8: Modules in Python Decision Control - GitHub PagesModules in Python • We can collect a bunch of Python functions and save them together in a file – Often called a module or library

Reminder:HowCanWeUseFunctions?

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

•  Wecanalsocallthem:–  Fromanotherfilealtogether–  (totestthemfrom)usingPytest

1/26/19 Matni,CS8,Wi19 8

Page 9: Modules in Python Decision Control - GitHub PagesModules in Python • We can collect a bunch of Python functions and save them together in a file – Often called a module or library

CreatingaModuleConsideracoupleoffunctionsthatwewroteandthatwe’dliketouseinotherPythonprograms:

#Doublingfunctiondefdbl(x):return2*x

#Halvingfunctiondefhalf(x):returnx/2

1/25/19 Matni,CS8,Wi19 9

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

Page 10: Modules in Python Decision Control - GitHub PagesModules in Python • We can collect a bunch of Python functions and save them together in a file – Often called a module or library

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

Page 11: Modules in Python Decision Control - GitHub PagesModules in Python • We can collect a bunch of Python functions and save them together in a file – Often called a module or library

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

Page 12: Modules in Python Decision Control - GitHub PagesModules in Python • We can collect a bunch of Python functions and save them together in a file – Often called a module or library

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

Page 13: Modules in Python Decision Control - GitHub PagesModules in Python • We can collect a bunch of Python functions and save them together in a file – Often called a module or library

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

Page 14: Modules in Python Decision Control - GitHub PagesModules in Python • We can collect a bunch of Python functions and save them together in a file – Often called a module or library

RelationalOperators•  Tocheckiftwoobjectsareequal,weuse:

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

1/26/19 Matni,CS8,Wi19 14

LessthanLessthanorequaltoGreaterthanGreaterthanorequaltoNotequalto

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

Page 15: Modules in Python Decision Control - GitHub PagesModules in Python • We can collect a bunch of Python functions and save them together in a file – Often called a module or library

WhatistheOutputoftheprint()statement?

a=3b=(a!=3)print(b)A.  TrueB.  FalseC.  3D.  Syntaxerror1/26/19 Matni,CS8,Wi19 15

Page 16: Modules in Python Decision Control - GitHub PagesModules in Python • We can collect a bunch of Python functions and save them together in a file – Often called a module or library

LogicOperators•  LogicAND

–  UseinPython:xandy–  PresentsaTrueoutputifbothxandyareTrue

•  LogicOR–  UseinPython:xory–  PresentsaTrueoutputifeitherxandyareTrue

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

1/26/19 Matni,CS8,Wi19 16

Page 17: Modules in Python Decision Control - GitHub PagesModules in Python • We can collect a bunch of Python functions and save them together in a file – Often called a module or library

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

1/26/19 Matni,CS8,Wi19 17

çFalseçTrue

çTrue

Page 18: Modules in Python Decision Control - GitHub PagesModules in Python • We can collect a bunch of Python functions and save them together in a file – Often called a module or library

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

Page 19: Modules in Python Decision Control - GitHub PagesModules in Python • We can collect a bunch of Python functions and save them together in a file – Often called a module or library

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

Page 20: Modules in Python Decision Control - GitHub PagesModules in Python • We can collect a bunch of Python functions and save them together in a file – Often called a module or library

ControllingtheFlowofaProgram•  Programswilloftenneedtomakedecisionsonwhattocontinuedoing–  Likecomingtoaforkintheroad…

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

1/27/19 Matni,CS8,Wi19 20

Page 21: Modules in Python Decision Control - GitHub PagesModules in Python • We can collect a bunch of Python functions and save them together in a file – Often called a module or library

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!")

Page 22: Modules in Python Decision Control - GitHub PagesModules in Python • We can collect a bunch of Python functions and save them together in a file – Often called a module or library

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!!!!!")

Page 23: Modules in Python Decision Control - GitHub PagesModules in Python • We can collect a bunch of Python functions and save them together in a file – Often called a module or library

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)

Page 24: Modules in Python Decision Control - GitHub PagesModules in Python • We can collect a bunch of Python functions and save them together in a file – Often called a module or library

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?

Page 25: Modules in Python Decision Control - GitHub PagesModules in Python • We can collect a bunch of Python functions and save them together in a file – Often called a module or library

YOURTO-DOsq  FinishreadingChapter5

q  We’llbediscussingloopsonWednesday

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

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

Page 26: Modules in Python Decision Control - GitHub PagesModules in Python • We can collect a bunch of Python functions and save them together in a file – Often called a module or library

1/25/19 Matni,CS8,Wi19 26