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/
03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague
2
PROBLEMSOLVING!2
03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague
• Problemformulation(input/output)
• Formalism(math?)
• Algorithm(theidea!)
• Implementation(engineering)
• Testing(arewegood?)
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 """)
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!
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
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
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
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//
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
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(**)
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)
12
INPUT12
03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague
sourcehttp://openbookproject.net/thinkcs/python/english3e/variables_expressions_statements.html
• Built-infunctiontogetinputfromauser:
input(”Messagetotheuser!”)
• Userinputisstoredasstring• Combinewithtypeconversion
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
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
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
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
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!
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
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)
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
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
22
BOOLEANALGEBRA22
03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague
sourcehttp://openbookproject.net/thinkcs/python/english3e/conditionals.html
23
CONDITIONALEXECUTION23
03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague
sourcehttp://openbookproject.net/thinkcs/python/english3e/conditionals.html
• ConditionIF– ELSE• Conditionalstatement– theabilitytocheckconditionsandchangethebehavioroftheprogramaccordingly
24
CONDITIONALEXECUTION24
03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague
sourcehttp://openbookproject.net/thinkcs/python/english3e/conditionals.html
• ConditionIFonly• NoELSEstatement• Tocontrolflowonlyforspecificcondition
25
CONDITIONALEXECUTION25
03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague
sourcehttp://openbookproject.net/thinkcs/python/english3e/conditionals.html
• ConditionchainingIF– ELIF– ELSE
• Recommendation:handlealldistinctiveoptionsbyseparatecondition,useelsetohandleallother
26
CONDITIONALEXECUTION26
03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague
sourcehttp://openbookproject.net/thinkcs/python/english3e/conditionals.html
• Nestingconditionsbuildshierarchyofdecisions(decisiontrees)
• Nestingmayreducereadabilityandclarity
27
CONDITIONALEXECUTION27
03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague
sourcehttp://book.pythontips.com/en/latest/for_-_else.html
• Earlyreturn/earlybreak• Canbeusedtospeed-upcodeexecution• Specialcondition:FOR– ELSE
28
BOOLEANALGEBRA– LOGICOPPOSITES28
03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague
sourcehttp://openbookproject.net/thinkcs/python/english3e/conditionals.html
• Eachofthesixrelationaloperatorshasalogicalopposite• Recommendation:not operatorsmayreducereadability,uselogicaloppositesinstead
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
30
DEMORGAN‘SLAWS30
03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague
sourcehttp://openbookproject.net/thinkcs/python/english3e/conditionals.html
• Example:supposewecanslaythedragononlyifourmagicswordischargedto90%orhigherand wehave100ormoreenergyunitsinourprotectiveshield
31
EXAMPLE31
03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague
sourcehttp://openbookproject.net/thinkcs/python/english3e/conditionals.html
• Example: completethetable..
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/