prg –programming essentials - cvut.cz · •functions, int(), float()and str()convert their...

32
PRG – PROGRAMMING ESSENTIALS 1 Lecture 2 – Program flow, Conditionals, Loops https://cw.fel.cvut.cz/wiki/courses/be5b33prg/start Michal Reinštein Czech Technical University in Prague, Faculty of Electrical Engineering, Dept. of Cybernetics, Center for Machine Perception http://cmp.felk.cvut.cz/~reinsmic/ [email protected] 03/12/2017 Michal Reinštein, Czech Technical University in Prague

Upload: others

Post on 08-Jul-2020

27 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: PRG –PROGRAMMING ESSENTIALS - cvut.cz · •Functions, int(), float()and str()convert their arguments into types int , float and str respectively. •The type converter float()

1

PRG– PROGRAMMINGESSENTIALS1

Lecture2– Programflow,Conditionals,Loopshttps://cw.fel.cvut.cz/wiki/courses/be5b33prg/start

MichalReinšteinCzechTechnicalUniversityinPrague,

FacultyofElectricalEngineering,Dept.ofCybernetics,CenterforMachinePerceptionhttp://cmp.felk.cvut.cz/~reinsmic/

[email protected]

03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague

Page 2: PRG –PROGRAMMING ESSENTIALS - cvut.cz · •Functions, int(), float()and str()convert their arguments into types int , float and str respectively. •The type converter float()

2

PROBLEMSOLVING!2

03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague

• Problemformulation(input/output)

• Formalism(math?)

• Algorithm(theidea!)

• Implementation(engineering)

• Testing(arewegood?)

Page 3: PRG –PROGRAMMING ESSENTIALS - cvut.cz · •Functions, int(), float()and str()convert their arguments into types int , float and str respectively. •The type converter float()

3

DATATYPES3

03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague

sourcehttp://openbookproject.net/thinkcs/python/english3e/variables_expressions_statements.html

• Integers(int) 1,10,124• Strings(str) ”Hello,World!”• Float(float) 1.0,9.999

• StringsinPythoncanbeenclosedineithersinglequotes(')ordoublequotes("),orthreeofeach(''' or """)

Page 4: PRG –PROGRAMMING ESSENTIALS - cvut.cz · •Functions, int(), float()and str()convert their arguments into types int , float and str respectively. •The type converter float()

4

VARIABLES4

03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague

sourcehttp://openbookproject.net/thinkcs/python/english3e/variables_expressions_statements.html

• Weusevariablestoremember things!• The assignmentstatement givesavaluetoavariable• Donotconfuse= and== !

=isassignment tokensuchthatname_of_variable =value==isoperatortotestequality

• Keypropertyofavariablethatwecanchangeitsvalue• Namingconvention:withfreedomcomesresponsibility!

Page 5: PRG –PROGRAMMING ESSENTIALS - cvut.cz · •Functions, int(), float()and str()convert their arguments into types int , float and str respectively. •The type converter float()

5

VARIABLES5

03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague

sourcehttp://openbookproject.net/thinkcs/python/english3e/variables_expressions_statements.html

• Thelongerlifethelongername:very_long_name_of_my_var• Themoreimportantthelongername• Meaningfulnamedoesnotaddthemeaningjustbyitself,

thecodemustdothis!• Illegalnamecausesasyntaxerror• Capitals:Variable vsvariable

cannotbeginwithanumber

this$isillegalcharacter

classisreservedkeyword

Page 6: PRG –PROGRAMMING ESSENTIALS - cvut.cz · •Functions, int(), float()and str()convert their arguments into types int , float and str respectively. •The type converter float()

6

KEYWORDS6

03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague

sourcehttp://openbookproject.net/thinkcs/python/english3e/variables_expressions_statements.html

• Pythonkeywordshavespecial purpose• Alwayschoosenamesmeaningful tohumanreaders• Usecomments(#)and blanklinestoimprovereadability

Page 7: PRG –PROGRAMMING ESSENTIALS - cvut.cz · •Functions, int(), float()and str()convert their arguments into types int , float and str respectively. •The type converter float()

7

BUILT-INFUNCTIONS7

03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague

sourcehttp://openbookproject.net/thinkcs/python/english3e/variables_expressions_statements.html

• Built-infunctionshavespecial purpose• Studyhttps://docs.python.org/3.4/library/functions.html

Page 8: PRG –PROGRAMMING ESSENTIALS - cvut.cz · •Functions, int(), float()and str()convert their arguments into types int , float and str respectively. •The type converter float()

8

OPERATORS&OPERANDS8

03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague

sourcehttp://openbookproject.net/thinkcs/python/english3e/variables_expressions_statements.html

• OPERAND OPERATOR OPERAND• Operatorsarespecialtokensthatrepresentcomputationslikeaddition,subtraction,multiplication,division etc

• Thevaluestheoperatorusesarecalledoperands• Whenavariablenameappearsintheplaceofanoperand,itisreplacedwithitsvaluebeforetheoperationisperformed

• Division/ vsfloor division//

Page 9: PRG –PROGRAMMING ESSENTIALS - cvut.cz · •Functions, int(), float()and str()convert their arguments into types int , float and str respectively. •The type converter float()

9

TYPECONVERSION9

03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague

sourcehttp://openbookproject.net/thinkcs/python/english3e/variables_expressions_statements.html

• Functions,int(),float() andstr() converttheirargumentsintotypesint,float andstr respectively.

• Thetypeconverter float() canturnaninteger,afloat,orasyntacticallylegalstring intoafloat

• Thetypeconverter str() turnsitsargumentintoastring• Onesymbolcanhavedifferentmeaningdependingonthedatatype(s)- try& explore& understand

Page 10: PRG –PROGRAMMING ESSENTIALS - cvut.cz · •Functions, int(), float()and str()convert their arguments into types int , float and str respectively. •The type converter float()

10

ORDEROFOPERATIONS– PEMDAS10

03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague

sourcehttp://openbookproject.net/thinkcs/python/english3e/variables_expressions_statements.html

• Evaluationdependsonthe rulesofprecedence:1. Parentheses(fororder,readability)2. Exponentiation3. MultiplicationandDivision4. AdditionandSubtraction• Orderleft-to-right evaluationonthesamelevel,withtheexceptionofexponentiation(**)

Page 11: PRG –PROGRAMMING ESSENTIALS - cvut.cz · •Functions, int(), float()and str()convert their arguments into types int , float and str respectively. •The type converter float()

11

OPERATIONSONSTRINGS11

03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague

sourcehttp://openbookproject.net/thinkcs/python/english3e/variables_expressions_statements.html

• Youcannotperformmathematicaloperationsonstrings,evenifthestringslooklikenumbers

• The + operatorrepresents concatenation,notaddition• The * operatoralsoworksonstrings;itperformsrepetition(oneoftheoperandshastobeastring;theotherhastobeaninteger)

Page 12: PRG –PROGRAMMING ESSENTIALS - cvut.cz · •Functions, int(), float()and str()convert their arguments into types int , float and str respectively. •The type converter float()

12

INPUT12

03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague

sourcehttp://openbookproject.net/thinkcs/python/english3e/variables_expressions_statements.html

• Built-infunctiontogetinputfromauser:

input(”Messagetotheuser!”)

• Userinputisstoredasstring• Combinewithtypeconversion

Page 13: PRG –PROGRAMMING ESSENTIALS - cvut.cz · •Functions, int(), float()and str()convert their arguments into types int , float and str respectively. •The type converter float()

13

COMPOSITION13

03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague

sourcehttp://openbookproject.net/thinkcs/python/english3e/variables_expressions_statements.html

• Combinationoftheelementsofaprogram:variables,expressions,statements,andfunctioncalls

• Oneofthemostusefulfeaturesofprogramminglanguages• Takesmallbuildingblocksand compose themintolargerchunks

Page 14: PRG –PROGRAMMING ESSENTIALS - cvut.cz · •Functions, int(), float()and str()convert their arguments into types int , float and str respectively. •The type converter float()

14

MODULUSOPERATOR14

03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague

sourcehttp://openbookproject.net/thinkcs/python/english3e/variables_expressions_statements.html

• The modulusoperator worksonintegers (integerexpressions)• Definition:modulusistheremainder whenthefirstnumberisdividedbythesecond

• Modulusoperatorisapercentsign%• Syntaxisthesameasforotheroperators• Thesameprecedence asthemultiplication operator

Page 15: PRG –PROGRAMMING ESSENTIALS - cvut.cz · •Functions, int(), float()and str()convert their arguments into types int , float and str respectively. •The type converter float()

15

THEFORLOOP15

03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague

sourcehttp://openbookproject.net/thinkcs/python/english3e/hello_little_turtles.html

• Thevariable friend atline1isthe loopvariable• Lines2and3arethe loopbody• Theloopbodyisalwaysindented• Theindentation determinesexactlywhatstatements are“inthebodyoftheloop”

• Attheendofeachexecutionofthebodyoftheloop,Pythonreturnstothe for statement,toseeiftherearemoreitemstobehandled,andtoassignthenextoneto theloopvariable

Page 16: PRG –PROGRAMMING ESSENTIALS - cvut.cz · •Functions, int(), float()and str()convert their arguments into types int , float and str respectively. •The type converter float()

16

THEFORLOOP16

03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague

sourcehttp://openbookproject.net/thinkcs/python/english3e/hello_little_turtles.html

Oneach iteration or pass oftheloop:• Checktoseeiftherearestillmoreitemstobeprocessed• Iftherearenoneleft(the terminatingcondition oftheloop)theloophasfinished

• Ifthereareitemsstilltobeprocessed,theloopvariableisupdated torefertothenextiteminthelist

• Programexecutioncontinuesatthenextstatementaftertheloopbody

• Toexplore:earlybreak,orfor– elseloop

Page 17: PRG –PROGRAMMING ESSENTIALS - cvut.cz · •Functions, int(), float()and str()convert their arguments into types int , float and str respectively. •The type converter float()

17

THEFORLOOP– CONTROLFLOW17

03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague

sourcehttp://openbookproject.net/thinkcs/python/english3e/hello_little_turtles.html

• Controlflow(controlofthe flowofexecution oftheprogram)

• Asprogramexecutes,theinterpreteralwayskeepstrackofwhichstatementisabouttobeexecuted

• Controlflowuntilnowhasbeenstrictlytoptobottom,onestatementatatime,the for loopchangesthis!

Page 18: PRG –PROGRAMMING ESSENTIALS - cvut.cz · •Functions, int(), float()and str()convert their arguments into types int , float and str respectively. •The type converter float()

18

BOOLEANVALUES&EXPRESSIONS18

03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague

sourcehttp://openbookproject.net/thinkcs/python/english3e/conditionals.html

• Testconditionsandchangetheprogrambehaviordependingontheoutcomeofthetests

• Boolean valueiseitherTrue orFalse• NamedaftertheBritishmathematician,GeorgeBoole,whofirstformulated Booleanalgebra

Page 19: PRG –PROGRAMMING ESSENTIALS - cvut.cz · •Functions, int(), float()and str()convert their arguments into types int , float and str respectively. •The type converter float()

19

BOOLEANVALUES&EXPRESSIONS19

03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague

sourcehttp://openbookproject.net/thinkcs/python/english3e/conditionals.html

• Booleanexpression isanexpressionthatevaluatestoproducearesultwhichisaBooleanvalue

• Sixcommon comparisonoperators whichallproducea bool result(differentfromthemathematicalsymbols)

Page 20: PRG –PROGRAMMING ESSENTIALS - cvut.cz · •Functions, int(), float()and str()convert their arguments into types int , float and str respectively. •The type converter float()

20

LOGICALOPERATORS20

03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague

sourcehttp://openbookproject.net/thinkcs/python/english3e/conditionals.html

• three logicaloperators, and, or,and not,thatallowtobuildmorecomplexexpressionsfromsimpleBooleanexpressions

• semantics(meaning)oftheseoperatorsissimilartonaturallanguageequivalent

Page 21: PRG –PROGRAMMING ESSENTIALS - cvut.cz · •Functions, int(), float()and str()convert their arguments into types int , float and str respectively. •The type converter float()

21

TRUTHTABLES21

03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague

sourcehttp://openbookproject.net/thinkcs/python/english3e/conditionals.html

Short-circuitevaluation:• OR – iftheexpressionontheleftofthe operatoryieldsTrue,Pythondoesnotevaluatetheexpressionontheright

• AND – iftheexpressionontheleftyields False,Pythondoesnotevaluatetheexpressionontheright.

• Truthtable– listofallthepossibleinputstogivetheresultsforthelogicaloperators

Page 22: PRG –PROGRAMMING ESSENTIALS - cvut.cz · •Functions, int(), float()and str()convert their arguments into types int , float and str respectively. •The type converter float()

22

BOOLEANALGEBRA22

03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague

sourcehttp://openbookproject.net/thinkcs/python/english3e/conditionals.html

Page 23: PRG –PROGRAMMING ESSENTIALS - cvut.cz · •Functions, int(), float()and str()convert their arguments into types int , float and str respectively. •The type converter float()

23

CONDITIONALEXECUTION23

03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague

sourcehttp://openbookproject.net/thinkcs/python/english3e/conditionals.html

• ConditionIF– ELSE• Conditionalstatement– theabilitytocheckconditionsandchangethebehavioroftheprogramaccordingly

Page 24: PRG –PROGRAMMING ESSENTIALS - cvut.cz · •Functions, int(), float()and str()convert their arguments into types int , float and str respectively. •The type converter float()

24

CONDITIONALEXECUTION24

03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague

sourcehttp://openbookproject.net/thinkcs/python/english3e/conditionals.html

• ConditionIFonly• NoELSEstatement• Tocontrolflowonlyforspecificcondition

Page 25: PRG –PROGRAMMING ESSENTIALS - cvut.cz · •Functions, int(), float()and str()convert their arguments into types int , float and str respectively. •The type converter float()

25

CONDITIONALEXECUTION25

03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague

sourcehttp://openbookproject.net/thinkcs/python/english3e/conditionals.html

• ConditionchainingIF– ELIF– ELSE

• Recommendation:handlealldistinctiveoptionsbyseparatecondition,useelsetohandleallother

Page 26: PRG –PROGRAMMING ESSENTIALS - cvut.cz · •Functions, int(), float()and str()convert their arguments into types int , float and str respectively. •The type converter float()

26

CONDITIONALEXECUTION26

03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague

sourcehttp://openbookproject.net/thinkcs/python/english3e/conditionals.html

• Nestingconditionsbuildshierarchyofdecisions(decisiontrees)

• Nestingmayreducereadabilityandclarity

Page 27: PRG –PROGRAMMING ESSENTIALS - cvut.cz · •Functions, int(), float()and str()convert their arguments into types int , float and str respectively. •The type converter float()

27

CONDITIONALEXECUTION27

03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague

sourcehttp://book.pythontips.com/en/latest/for_-_else.html

• Earlyreturn/earlybreak• Canbeusedtospeed-upcodeexecution• Specialcondition:FOR– ELSE

Page 28: PRG –PROGRAMMING ESSENTIALS - cvut.cz · •Functions, int(), float()and str()convert their arguments into types int , float and str respectively. •The type converter float()

28

BOOLEANALGEBRA– LOGICOPPOSITES28

03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague

sourcehttp://openbookproject.net/thinkcs/python/english3e/conditionals.html

• Eachofthesixrelationaloperatorshasalogicalopposite• Recommendation:not operatorsmayreducereadability,uselogicaloppositesinstead

Page 29: PRG –PROGRAMMING ESSENTIALS - cvut.cz · •Functions, int(), float()and str()convert their arguments into types int , float and str respectively. •The type converter float()

29

DEMORGAN‘SLAWS29

03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague

sourcehttp://openbookproject.net/thinkcs/python/english3e/conditionals.html

• DeMorgan’slaws rulesallowtheexpressionof conjunctions and disjunctions intermsofeachothervia negation

• Example:supposewecanslaythedragononlyifourmagicswordischargedto90%orhigherand wehave100ormoreenergyunitsinourprotectiveshield

Page 30: PRG –PROGRAMMING ESSENTIALS - cvut.cz · •Functions, int(), float()and str()convert their arguments into types int , float and str respectively. •The type converter float()

30

DEMORGAN‘SLAWS30

03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague

sourcehttp://openbookproject.net/thinkcs/python/english3e/conditionals.html

• Example:supposewecanslaythedragononlyifourmagicswordischargedto90%orhigherand wehave100ormoreenergyunitsinourprotectiveshield

Page 31: PRG –PROGRAMMING ESSENTIALS - cvut.cz · •Functions, int(), float()and str()convert their arguments into types int , float and str respectively. •The type converter float()

31

EXAMPLE31

03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague

sourcehttp://openbookproject.net/thinkcs/python/english3e/conditionals.html

• Example: completethetable..

Page 32: PRG –PROGRAMMING ESSENTIALS - cvut.cz · •Functions, int(), float()and str()convert their arguments into types int , float and str respectively. •The type converter float()

32

REFERENCES32

03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague

Thislecturere-usesselectedpartsoftheOPENBOOKPROJECTLearningwithPython3(RLE)

http://openbookproject.net/thinkcs/python/english3e/index.htmlavailableunderGNUFreeDocumentationLicense Version1.3)

• Versiondate:October2012• byPeterWentworth,JeffreyElkner,AllenB.Downey,andChrisMeyers

(basedon2ndeditionbyJeffreyElkner,AllenB.Downey,andChrisMeyers)

• Sourcerepositoryisat https://code.launchpad.net/~thinkcspy-rle-team/thinkcspy/thinkcspy3-rle

• Forofflineuse,downloadazipfileofthehtmlorapdfversionfrom http://www.ict.ru.ac.za/Resources/cspw/thinkcspy3/