Lecture#03– IntroductiontoPythonandProgramming,ControlFlow
Erkut Erdem,AykutErdem&AydınKaya//Fall2017
BBM101IntroductiontoProgrammingI
MontyPythonandtheHolyGrail(1975)
Lasttime… Howtobuildcomputers
2
Memory
Control ALU PC
inst1inst2inst3..instN
A Simple HMMM Program
triangle1.hmmm: Calculate the approximate area of a triangle.
0 read r1 # Get base b
1 read r2 # Get height h
2 mul r1 r1 r2 # b times h into r1
3 setn r2 2
4 div r1 r1 r2 # Divide by 2
5 write r1
6 halt
$ python hmmmAssembler.py -f triangle1.hmmm -o triangle1.b
----------------------
| ASSEMBLY SUCCESSFUL |
----------------------
0 : 0000 0001 0000 0001 0 read r1 # Get base b
1 : 0000 0010 0000 0001 1 read r2 # Get height h
2 : 1000 0001 0001 0010 2 mul r1 r1 r2 # b times h into r1
3 : 0001 0010 0000 0010 3 setn r2 2
4 : 1001 0001 0001 0010 4 div r1 r1 r2 # Divide by 2
5 : 0000 0001 0000 0010 5 write r1
6 : 0000 0000 0000 0000 6 halt
$ python hmmmSimulator.py -f triangle1.b -n
4
5
10
4 / 14
A Simple HMMM Program
triangle1.hmmm: Calculate the approximate area of a triangle.
0 read r1 # Get base b
1 read r2 # Get height h
2 mul r1 r1 r2 # b times h into r1
3 setn r2 2
4 div r1 r1 r2 # Divide by 2
5 write r1
6 halt
$ python hmmmAssembler.py -f triangle1.hmmm -o triangle1.b
----------------------
| ASSEMBLY SUCCESSFUL |
----------------------
0 : 0000 0001 0000 0001 0 read r1 # Get base b
1 : 0000 0010 0000 0001 1 read r2 # Get height h
2 : 1000 0001 0001 0010 2 mul r1 r1 r2 # b times h into r1
3 : 0001 0010 0000 0010 3 setn r2 2
4 : 1001 0001 0001 0010 4 div r1 r1 r2 # Divide by 2
5 : 0000 0001 0000 0010 5 write r1
6 : 0000 0000 0000 0000 6 halt
$ python hmmmSimulator.py -f triangle1.b -n
4
5
10
4 / 14
poweroutput
input
0.0V0.5V
2.8V3.3V
0 1 0
Boolean Algebra and Functions
Any function of boolean variables, no matter how complex, can be expressed in termsof AND, OR, and NOT
Consider the proposition “if you score over 93% in this course, then you will get an A”
The truth values for the above proposition is given by the “implication” function(x =) y) having the following truth table
x y x =) y
0 0 10 1 11 0 01 1 1
The function can be compactly written as NOT x OR x AND y (or x̄+ xy)
10 / 21
TheHarveyMudd MiniatureMachine(HMMM)
LectureOverview• Programminglanguages(PLs)
• IntroductiontoPythonandProgramming
• ControlFlow
3
Disclaimer:Muchofthematerialandslidesforthislecturewereborrowedfrom—E.Grimson,J.Guttag andC.Terman MIT6.0001class—RuthAnderson,MichaelErnstandBillHowe’sCSE140class—SwamiIyer’s Umass BostonCS110class
LectureOverview• Programminglanguages(PLs)
• IntroductiontoPythonandProgramming
• ControlFlow
4
ProgrammingLanguages
• Syntaxandsemantics
• DimensionsofaPL
• Programmingparadigms
ProgrammingLanguages• Anartificiallanguagedesignedtoexpresscomputationsthatcanbeperformedbyamachine,particularlyacomputer.
• Canbeusedtocreateprogramsthatcontrolthebehaviorofamachine,toexpressalgorithmsprecisely,orasamodeofhumancommunication.
• e.g.,C,C++,Java,Python,Prolog,Haskell,Scala,etc..
CreatingComputerPrograms• Eachprogramminglanguageprovidesasetofprimitiveoperations.
• Eachprogramminglanguageprovidesmechanismsforcombiningprimitivestoformmorecomplex,butlegal,expressions.
• Eachprogramminglanguageprovidesmechanismsfordeducingmeaningsorvaluesassociatedwithcomputationsorexpressions.
AspectsofLanguages• Primitiveconstructs– Programming language– numbers,strings,simpleoperators
– English– words
• Syntax– whichstringsofcharactersandsymbolsarewell-formed– Programminglanguage–we’llgettospecificsshortly,butfor example3.2+3.2isavalidCexpression
– English– “catdog boy”is notsyntacticallyvalid, asnotinformofacceptablesentence
AspectsofLanguages• Staticsemantics– whichsyntacticallyvalidstringshave a meaning
– English– “Iarebig”hasform<noun><intransitiveverb><noun>,sosyntacticallyvalid,butisnotvalidEnglishbecause“I”issingular,“are”isplural
– Programminglanguage– forexample,<literal><operator><literal>isavalidsyntacticform,but2.3/’abc’isastaticsemanticerror
AspectsofLanguages• Semantics– whatisthemeaningassociatedwithasyntacticallycorrectstringofsymbolswithnostaticsemanticerrors
– English– canbeambiguous• “Theysawthemanwiththetelescope.”
– Programming languages – alwayshasexactlyonemeaning• Butmeaning(orvalue)maynotbewhatprogrammerintended
WhereCanThingsGoWrong?• Syntacticerrors
– Commonbuteasilycaughtbycomputer
• Staticsemanticerrors– Somelanguagescheckcarefullybeforerunning,otherscheck
whileinterpretingtheprogram– Ifnotcaught,behaviorofprogramisunpredictable
• Programsdon’thavesemanticerrors,butmeaningmaynotbewhatwasintended– Crashes(stopsrunning)– Runsforever– Producesananswer,butnotprogrammer’s intent
OurGoal• Learnthesyntaxandsemanticsofaprogramminglanguage
• Learnhowtousethoseelementstotranslate“recipes”forsolvingaproblemintoaform thatthecomputercanusetodo theworkforus
• Computationalmodesofthoughtenableustouseasuiteofmethodstosolveproblems
DimensionsofaProgrammingLanguageLow-levelvs.High-level
• Distinctionaccordingtothelevelofabstraction
• Inlow-levelprogramminglanguages(e.g.Assembly),thesetofinstructionsusedincomputationsareverysimple(nearlyatmachinelevel)
• Ahigh-levelprogramminglanguage(e.g.Python,C,Java)hasamuchricherandmorecomplexsetofprimitives.
• Distinctionaccordingtotherangeofapplications
• Inageneralprogramminglanguage,thesetofprimitivessupportabroadrangeofapplications.
• Atargetedprogramminglanguage aimsataveryspecificsetofapplications.– e.g.,MATLAB(matrixlaboratory)isaprogramminglanguagespecificallydesignedfornumericalcomputing(matrixandvectoroperations)
DimensionsofaProgrammingLanguageGeneralvs.Targeted
• Distinctionaccordingtohowthesourcecodeisexecuted
• Ininterpretedlanguages(e.g.LISP),thesourcecodeisexecuteddirectlyatruntime(bytheinterpreter).– Interpretercontroltheflowoftheprogrambygoingthrougheachoneoftheinstructions.
• Incompiledlanguages(e.g.C),thesourcecodefirstneedstobetranslatedintoanobjectcode(bythecompiler)beforetheexecution.
DimensionsofaProgrammingLanguageInterpretedvs.Compiled
ProgrammingLanguageParadigms• Functional
• Treatscomputationastheevaluationofmathematicalfunctions(e.g.Lisp,Scheme,Haskell,etc.)
• Imperative• Describescomputationintermsofstatementsthatchangeaprogramstate(e.g.FORTRAN,BASIC,Pascal,C,etc.)
• Logical(declarative)• Expressesthelogicofacomputationwithoutdescribingitscontrolflow(e.g.Prolog)
• Objectoriented• Uses"objects"– datastructuresconsistingofdatafieldsandmethodstogetherwiththeirinteractions– todesignapplicationsandcomputerprograms(e.g.C++,Java,C#,Python,etc.)
ProgrammingLanguageParadigms• Functional
• Treatscomputationastheevaluationofmathematicalfunctions(e.g.Lisp,Scheme,Haskell,etc.)
• Imperative• Describescomputationintermsofstatementsthatchangeaprogramstate(e.g.FORTRAN,BASIC,Pascal,C,etc.)
• Logical(declarative)• Expressesthelogicofacomputationwithoutdescribingitscontrolflow(e.g.Prolog)
• Objectoriented• Uses"objects"– datastructuresconsistingofdatafieldsandmethodstogetherwiththeirinteractions– todesignapplicationsandcomputerprograms(e.g.C++,Java,C#,Python,etc.)
LectureOverview• Programminglanguages(PLs)
• IntroductiontoPythonandProgramming
• ControlFlow
18
ProgramminginPython• Ourprogrammingenvironment– Pythonprogramminglanguage
– PyCharm,anintegrateddevelopmentenvironment(IDE)
– Terminal
19
ProgramminginPython• ToprograminPython– Composeaprogrambytypingitintoafilenamed,say,helloworld.py
– Run(orexecute)theprogrambytypingpython helloworld.py intheterminalwindow
20
Editor(PyCharm)
compiler/interpreter(python)
helloworld.py Hello, World
InputandOutput• Bird’s-eyeviewofaPythonprogram
– Inputtypes:command-linearguments,standardinput,fileinput
– Outputtypes:standardoutput,fileoutput,graphicaloutput,audiooutput
21
my_program.pyinput output
InputandOutput• Command-lineargumentsaretheinputswelistafteraprogram
namewhenweruntheprogram
$ python my_program.py arg_1 arg_2 ... arg_n
• Thecommand-lineargumentscanbeaccessedwithinaprogram,suchasmy_program.py above,viathearray(akalist)sys.argv1assys.argv[1], sys.argv[2], . . . , sys.argv[n]
• Thenameoftheprogram(my_program.py)isstoredinsys.argv[0]
22
1ThesysmoduleprovidesaccesstovariablesandfunctionsthatinteractwiththePythoninterpreter
InputandOutputimport sys
print('Hi, ', end='')print(sys.argv[1], end='')print(’. How are you?')
23
$ python useargument.py Alice Hi, Alice. How are you? $ python useargument.py Bob Hi, Bob. How are you? $ python useargument.py CarolHi, Carol. How are you?
useargument.py
1.Pythonislikeacalculator 2.Avariableisacontainer
4.Aprogramisarecipe3.Differenttypescannotbecompared
24
1.PythonisLikeaCalculator
25
YouTypeExpressions.PythonComputesTheirValues.• 5• 3+4• 44/2• 2**3• 3*4+5*6• (72– 32)/9*5
26
Pythonhasanaturalandwell-definedsetofprecedencerulesthatfullyspecifytheorderinwhichtheoperatorsareappliedinanexpression• Forarithmeticoperations,multiplication
anddivisionareperformedbeforeadditionandsubtraction
• Whenarithmeticoperationshavethesameprecedence,theyareleftassociative,withtheexceptionoftheexponentiationoperator**,whichisrightassociative
• Wecanuseparenthesestooverrideprecedencerules
AnExpressionisEvaluatedFromtheInsideOut
• HowmanyexpressionsareinthisPythoncode?
(72– 32)/9.0*5
anexpression values
(72 – 32)/9.0 *5(40)/9.0 *540 /9.0 *54.44 *522.2
27
AnotherEvaluationExample
(72 – 32)/(9.0 *5)(40)/(9.0 *5)40 /(9.0 *5)40 /(45.0)40 /45.0.888
28
2.AVariableisaContainer
29
Avariableisanameassociatedwithadata-typevalue
VariablesHoldValues
• Recallvariablesfromalgebra:– Letx=2…– Lety=x…
• Toassignavariable,use“varname =expression”pi = 3.14pivar = 6*10**2322 = x #Error!
• Notallvariablenamesarepermitted!
Nooutputfromanassignmentstatement
30
• Variablenamesmustonlybeoneword(asinnospaces)
• Variablenamesmustbemadeupofonlyletters,numbers,andunderscore(_)
• Variablenamescannotbeginwithanumber
ChangingExistingVariables(“re-binding”or“re-assigning”)
x = 2xy =yx = 5xy
• “=”inanassignmentisnot apromiseofeternalequality– Thisisdifferent thanthemathematicalmeaningof“=”
• Evaluatinganexpressiongivesanew(copyofa)number,ratherthanchanginganexistingone
2x
31
HowanAssignmentisExecuted
1. Evaluatetheright-handsidetoavalue2. Storethatvalueinthevariable
x = 2print(x)y = xprint(y)z = x + 1print(z)x = 5print(x)print(y)print(z)
Stateofthecomputer: Printedoutput:
223523
x:2y:2z:3
x:5
Tovisualizeaprogram’sexecution:http://pythontutor.com
32
MoreExpressions:Conditionals(valueisTrue orFalse)22 > 4 #condition,orconditional22 < 4 #condition,orconditional22 == 4 …x = 100 #Assignment,not conditional!22 = 4 #Error!x >= 5x >= 100x >= 200not Truenot (x >= 200)3<4 and 5<64<3 or 5<6temp = 72water_is_liquid = (temp > 32 and temp < 212)
Numericoperators:+,*,**Booleanoperators:not,and,orMixedoperators:<,>=,==
33
MoreExpressions:strings• Astringrepresentstext
– 'Python'– myString = "BBM 101-Introduction to Programming"– ""
• Emptystringisnotthesameasanunboundvariable– "" and‘’arethesame
• Wecanspecifytab,newline,backslash,andsinglequotecharactersusingescapesequences’\t’,’\n’,’\\’,and’\’’,respectively
Operations:• Length:
– len(myString)
• Concatenation:– "Hacettepe" + " " + ' University'
• Containment/searching:– 'a' in myString– "a" in myString
34
Stringsruler1 = '1'ruler2 = ruler1 + ' 2 ' + ruler1 ruler3 = ruler2 + ' 3 ' + ruler2 ruler4 = ruler3 + ' 4 ' + ruler3 print(ruler1)print(ruler2)print(ruler3)print(ruler4)
35
11211213121121312141213121
3.DifferentTypescannotbeCompared
36
anInt = 2aString = "Hacettepe" anInt == aString # Error
TypesofValues
• Integers(int):-22,0,44– Arithmeticisexact– Somefunnyrepresentations:12345678901L
• Realnumbers(float,for“floatingpoint”):2.718,3.1415– Arithmeticisapproximate,e.g.,6.022*10**23
• Strings(str):"I love Python"," "
• Truthvalues(bool,for“Boolean”):True,False
GeorgeBoole37
OperationsBehavedifferentlyonDifferentTypes3.0 + 4.03 + 43 + 4.0"3" + "4" #Concatenation3 + "4" #Error3 + True #Error
Moral:Pythononlysometimes tellsyouwhenyoudosomethingthatdoesnotmakesense.
38
OperationsonDifferentTypes
15.0 / 4.0 3.75 3.7515 / 4 3.75 315.0 / 4 3.75 3.7515 / 4.0 3.75 3.75
15.0 // 4.0 3.015 // 4 315.0 // 4 3.015 // 4.0 3.0
39
BeforePythonversion3.5,operandusedtodeterminethetypeofdivision.
Python3.5 Python2.x
/:Division//:IntegerDivision
TypeConversion
float(15) 15.0int(15.0) 15int(15.5) 15int("15") 15str(15.5) 15.5float(15) / 4 3.75
40
AProgramisaRecipe
41
DesigntheAlgorithmBeforeCoding• Weshouldthink(designthealgorithm)beforecoding
• Algorithmicthinkingisthelogic.Also,calledproblemsolving
• Codingisthesyntax
• Makethisahabit
• Somestudentsdonotfollowthispracticeandtheygetchallengedinalltheircoursesandcareers!
42
WhatisaProgram?• Aprogramisasequenceofinstructions
• Thecomputerexecutesoneaftertheother,asiftheyhadbeentypedtotheinterpreter
• Savingyourworkasaprogramisbetterthanre-typingfromscratch
43
x = 1y = 2x + yprint(x + y)print("The sum of", x, "and", y, "is", x+y)
Theprint() Statement
• Theprint statementalwaysprintsoneline– Thenextprintstatementprintsbelowthatone
• Write0ormoreexpressionsafterprint,separatedbycommas– Intheoutput,thevaluesareseparatedbyspaces
• Examples:x = 1y = 2print(3.1415)print(2.718, 1.618)print()print(20 + 2, 7 * 3, 4 * 5)print("The sum of", x, end="")print(" and", y, "is", x+y)
44
3.14152.718 1.618
22 21 20The sum of 1 and 2 is 3
Toavoidnewline
Exercise:ConvertTemperatures• Makeatemperatureconversionchartasthefollowing
• FahrenheittoCentigrade,forFahrenheitvaluesof:-40,0,32,68,98.6,212
• C=(F- 32)× 5/9
• Output:Fahrenheit Centigrade-40 -40.00 -17.777832 0.068 20.098.6 37.0212 100.0
• YouhavecreatedaPythonprogram!
• (Itdoesn’thavetobethistedious,anditwon’tbe.)
45
Expressions,Statements,andPrograms• Anexpressionevaluatestoavalue
3 + 4pi * r**2
• Astatementcausesaneffectpi = 3.14159print(pi)
• Expressionsappearwithinotherexpressionsandwithinstatements(fahr – 32) * (5.0 / 9)print(pi * r**2)
• Astatementmaynot appearwithinanexpression3 + print(pi) #Error!
• Aprogramismadeupofstatements– Aprogramshoulddosomethingorcommunicateinformation
46
1.Pythonislikeacalculator 2.Avariableisacontainer
4.Aprogramisarecipe3.Differenttypescannotbecompared
47
ProgrammingLanguages• Aprogramminglanguageisa“language”towriteprogramsin,
suchasPython,C,C++,Java
• Theconceptofprogramminglanguagesarequitesimilar
• Python:
• Java:
• Pythonissimpler!That’swhywearelearningitfirstJ
48
print("Hello, World!")
public static void main(String[] args) {System.out.println("Hello, World!");
}
EvolutionofProgrammingLanguages
49
The2017TopProgramming Languages
• https://spectrum.ieee.org/computing/software/the-2017-top-programming-languages 50
51
http://carlche
o.com/startcoding
LectureOverview• Programminglanguages(PLs)
• IntroductiontoPythonandProgramming
• ControlFlow
52
Repeatingyourself
Makingdecisions
53
TemperatureConversionChartRecalltheexercisefromthepreviouslecture
fahr = 30cent = (fahr -32)/9.0*5print(fahr, cent)fahr = 40cent = (fahr -32)/9.0*5print(fahr, cent)fahr = 50cent = (fahr -32)/9.0*5print(fahr, cent)fahr = 60cent = (fahr -32)/9.0*5print(fahr, cent)fahr = 70cent = (fahr -32)/9.0*5print(fahr, cent)Print("All done")
54
Output:30 -1.1140 4.4450 10.060 15.5570 21.11All done
TemperatureConversionChartAbetterwaytorepeatyourself:
55
for f in [30,40,50,60,70]:print(f, (f-32)/9.0*5)
print("All done")
Loopbodyisindented
Alist
Indentationissignificant
for loop
Executethebody5times:• oncewithf=30• oncewithf=40• oncewithf=50• oncewithf=60• oncewithf=70
loopvariableoriterationvariable
Output:30 -1.1140 4.4450 10.060 15.5570 21.11All done
Colonisrequired
i = 1print(i)i = 4 print(i)i = 9print(i)
HowaLoopisExecuted:TransformationApproach
for i in [1,4,9]:print(i)
Stateofthecomputer: Printedoutput:
149
i:1i:4i:9
Idea:convertafor loopintosomethingweknowhowtoexecute
1. Evaluatethesequenceexpression2. Writeanassignmenttotheloop
variable,foreachsequenceelement
3. Writeacopyoftheloopaftereachassignment
4. Executetheresultingstatements
56
for i in [1,4,9]:print(i)
HowaLoopisExecuted:DirectApproach
Printedoutput:
149
i:1i:4i:9
CurrentlocationinlistStateofthecomputer:
1. Evaluatethesequenceexpression2. Whiletherearesequence
elementsleft:a) Assigntheloopvariabletothenext
remainingsequenceelementb) Executetheloopbody
57
TheBodycanbeMultipleStatements
Executewholebody,thenexecutewholebodyagain,etc.
for i in [3,4,5]:print("Start body")print(i)print(i*i)
Convention:oftenusei orj asloopvariableifvaluesareintegersThisisanexceptiontotherulethatvariablenamesshouldbedescriptive
Output:Startbody39Startbody416Startbody525
NOT:StartbodyStartbodyStartbody34591625
loopbody:3statements
58
IndentationinLoopisSignificant
• Everystatementinthebodymusthaveexactlythesameindentation• That’showPythonknowswherethebodyendsfor i in [3,4,5]:
print("Start body")print(i)
print(i*i)
• Comparetheresultsoftheseloops:for f in [30,40,50,60,70]:
print(f, (f-32)/9.0*5)print("All done")
for f in [30,40,50,60,70]:print(f, (f-32)/9.0*5)print("All done")
Error!
59
TheBodycanbeMultipleStatements
Howmanystatementsdoesthisloopcontain?
for i in [0,1]:print("Outer", i)for j in [2,3]:print(" Inner", j)print(" Sum", i+j)
print("Outer", i)
Whatistheoutput?
Output:Outer0Inner2Sum2Inner3Sum3
Outer0Outer1Inner2Sum3Inner3Sum4
Outer1
loopbody:3statements“nested”
loopbody:2statements
60
Keyidea:1. Assigneachsequenceelementtotheloopvariable2. Duplicatethebody
UnderstandLoopsThroughtheTransformationApproach
for i in [0,1]:print("Outer", i)for j in [2,3]:print(" Inner", j)
i = 0print("Outer", i)for j in [2,3]:print(" Inner", j)
i = 1print("Outer", i)for j in [2,3]:print(" Inner", j)
i = 0print("Outer", i)j = 2print(" Inner", j)j = 3print(" Inner", j)i = 1print("Outer", i)for j in [2,3]:print(" Inner", j)
61
FixThisLoop
# Goal: print 1, 2, 3, …, 48, 49, 50for tens_digit in [0, 1, 2, 3, 4]:for ones_digit in [1, 2, 3, 4, 5, 6, 7, 8, 9]:print(tens_digit * 10 + ones_digit)
Whatdoesitactuallyprint?Howcanwechangeittocorrectitsoutput?
Moral:Watchoutforedgeconditions (beginningorendofloop)
62
SomeFixes# Goal: print 1, 2, 3, …, 48, 49, 50
for tens_digit in [0, 1, 2, 3, 4]:for ones_digit in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]:print(tens_digit * 10 + ones_digit + 1)
for tens_digit in [0, 1, 2, 3, 4]:for ones_digit in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:print(tens_digit * 10 + ones_digit)
for tens_digit in [1, 2, 3, 4]:for ones_digit in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]:print(tens_digit * 10 + ones_digit)
print 50
• Analyzeeachoftheabove63
Reusingloopvariable(don’tdothis!)
TestYourUnderstandingofLoopsPuzzle1:
for i in [0,1]:print(i)
print(i)
Puzzle2:i = 5for i in []:
print(i)
Puzzle3:for i in [0,1]:
print("Outer", i)for i in [2,3]:
print(" Inner", i)print("Outer", i)
innerloopbody
outerloopbody
Outer0Inner2Inner3Outer3Outer1Inner2Inner3Outer3
011
Output:
(nooutput)
64
TheRangeFunction
Asanimplicitlist:for i in range(5):
… body …
range(5) =[0,1,2,3,4]
range(1,5) =[1,2,3,4]
range(1,10,2) =[1,3,5,7,9]
Thelist[0,1,2,3,4]
Upperlimit(exclusive)
Lowerlimit(inclusive)
step(distancebetweenelements)
65
DecomposingaListComputation
• Tocomputeavalueforalist:– Computeapartialresultforallbutthelastelement– Combinethepartialresultwiththelastelement
Example:sumofalist:
[3,1,4,1,5,9,2,6,5]
Listb
Lista
sum(Lista)=sum(Listb)+5sum(Listb)=sum(Listc)+6…sum(Listy)=sum(Listz)+3sum(emptylist)=0
Listc
Listy
Listz
66
HowtoProcessaList:OneElementataTime• Acommonpatternwhenprocessingalist:
result = initial_valuefor element in list:result = updated result
use result
• initial_value isacorrectresultforanemptylist
• Aseachelementisprocessed,result isacorrectresultforaprefixofthelist
• Whenallelementshavebeenprocessed,result isacorrectresultforthewholelist
# Sum of a listresult = 0for element in mylist:result = result + element
print result
67
SomeLoops# Sum of a list of values, what values?result = 0for element in range(5): # [0,1,2,3,4]
result = result + elementprint("The sum is: " + str(result))
# Sum of a list of values, what values?result = 0for element in range(5,1,-1):
result = result + elementprint("The sum is:", result)
# Sum of a list of values, what values?result = 0for element in range(0,8,2):
result = result + elementprint("The sum is:", result)
# Sum of a list of values, what values?result = 0size = 5for element in range(size):
result = result + elementprint("When size = " + str(size) + ", the result is " + str(result))
68
Thesumis:10
5,4,3,2Thesumis:14
0,2,4,6Thesumis:12
0,1,2,3,4Whensize=5,theresultis10
divisorpattern.py: Acceptintegercommand-lineargumentn.Writetostandardoutputann-by-n tablewithanasteriskinrowi andcolumnjifeitheri dividesjorjdividesi.import sys
n = int(sys.argv[1])for i in range(1, n + 1):
for j in range(1, n + 1):if (i % j == 0) or (j % i == 0):
print(‘* ‘, end=‘‘) else:
print(‘ ‘, end=‘‘) print(i)
69
Nesting
divisorpattern.py: Accept integer command-line argument n. Write to standard output an n-by-n table with an asterisk in row iand column j if either i divides j or j divides i.
import stdioimport sys
n = int(sys.argv [1])for i in range(1, n + 1):
for j in range(1, n + 1):if (i % j == 0) or (j % i == 0):
stdio.write(’* ’)else:
stdio.write(’ ’)stdio.writeln(i)
$ python divisorpattern.py 3* * * 1* * 2* * 3
$ python divisorpattern.py 10* * * * * * * * * * 1* * * * * * 2* * * * 3* * * * 4* * * 5* * * * 6* * 7* * * * 8* * * 9* * * * 10
Variable trace (n = 3)
i j output----------------1 1 ’* ’1 2 ’* ’1 3 ’* 1\n’2 1 ’* ’2 2 ’* ’2 3 ’ 2\n’3 1 ’* ’3 2 ’ ’3 3 ’* 3\n’
12 / 18
ExamplesofListProcessing
• Productofalist:result = 1for element in mylist:result = result * element
• Maximumofalist:result = mylist[0]for element in mylist:result = max(result, element)
• Approximatethevalue3by1+2/3+4/9+8/27+16/81+…=(2/3)0 +(2/3)1 +(2/3)2 +(2/3)3 +…+(2/3)10result = 0for element in range(11):result = result + (2.0/3.0)**element
result = initial_valuefor element in list:result = updated result
Thefirstelementofthelist(countingfromzero)
70
ExercisewithLoops• Writeasimpleprogramtoaddvaluesbetweentwogiveninputsa,b
• e.g.,ifa=5,b=9,itreturnssumof(5+6+7+8+9)• Hint:wedidsome‘algorithmicthinking’and‘problemsolving’here!
71
a=5b=9total = 0for x in range(a, b+1):
total += xprint(total)
AnotherTypeofLoops• Thewhile loopisusedforrepeatedexecutionaslongasanexpressionistrue
72
n = 100s = 0counter = 1while counter <= n:
s = s + countercounter += 1
print("Sum of 1 until %d: %d" % (n,s))
Sum of 1 until 100: 5050
MakingDecisions• Howdowecomputeabsolutevalue?
abs(5) = 5
abs(0) = 0
abs(-22) = 22
73
AbsoluteValueSolutionIf thevalueisnegative,negateit.Otherwise,usetheoriginalvalue.
val = -10
# calculate absolute value of valif val < 0:
result = - valelse:
result = val
print(result)
val = -10
if val < 0:print(- val)
else:print(val)
74
Inthisexample,result willalwaysbeassignedavalue.
Anotherapproachthatdoesthesamethingwithoutusingresult:
AbsoluteValueSolutionAswithloops,asequenceofstatementscouldbeusedinplaceofasinglestatementinsideanifstatement:
val = -10
# calculate absolute value of valif val < 0:
result = - valprint("val is negative!")print("I had to do extra work!")
else:result = valprint("val is positive")
print(result)75
AbsoluteValueSolutionWhathappenshere?
val = 5
# calculate absolute value of valif val < 0:
result = - valprint("val is negative!")
else:for i in range(val):
print("val is positive!")result = val
print(result)
76
AnotherifItisnotrequiredthatanythinghappens…
val = -10
if val < 0:print("negative value!")
77
Whathappenswhenval =5?
Executiongetshereonlyif“height>100”isfalseAND“height>50”istrue
TheifBodycanbeAnyStatements
# height is in kmif height > 100:print("space")
else:if height > 50:print("mesosphere")
else:if height > 20:print("stratosphere")
else:print("troposphere")
Writtendifferently,butmoreefficient!# height is in kmif height > 100:print("space")
elif height > 50:print("mesosphere")
elif height > 20:print("stratosphere")
else:print("troposphere")
Writtendifferently!# height is in kmif height > 50:if height > 100:print("space")
else:print("mesosphere")
else:if height > 20:print("stratosphere")
else:print("troposphere")
thenclause
elseclause
t
f t
f
0 10 20 30 40 50 60 70 80 90 100
troposphere stratosphere mesosphere spacekmaboveearth
Executiongetshereonlyif“height>100”isfalse
78
Executiongetshereonlyif“height<=100”istrueAND“height>50”istrue
Version1
# height is in kmif height > 100:print("space")
else:if height > 50:print("mesosphere")
else:if height > 20:print("stratosphere")
else:print("troposphere")
thenclause
elseclause
t
e t
e
Executiongetshereonlyif“height<=100”istrue
0 10 20 30 40 50 60 70 80 90 100
troposphere stratosphere mesosphere spacekmaboveearth
Version1
# height is in kmif height > 100:print("space")
else:if height > 50:print("mesosphere")
else:if height > 20:print("stratosphere")
else:print("troposphere")
0 10 20 30 40 50 60 70 80 90 100
troposphere stratosphere mesosphere spacekmaboveearth
Version2
if height > 50:if height > 100:print("space")
else:print("mesosphere")
else:if height > 20:print("stratosphere")
else:print("troposphere")
0 10 20 30 40 50 60 70 80 90 100
troposphere stratosphere mesosphere spacekmaboveearth
Version3if height > 100:print("space")
elif height > 50:print("mesosphere")
elif height > 20:print("stratosphere")
else:print("troposphere")
ONEoftheprintstatementsisguaranteedtoexecute:whicheverconditionitencountersfirstthatistrue
0 10 20 30 40 50 60 70 80 90 100
troposphere stratosphere mesosphere spacekmaboveearth
OrderMatters# version 3if height > 100:print("space")
elif height > 50:print("mesosphere")
elif height > 20:print("stratosphere")
else:print("troposphere")
# broken version 3if height > 20:print("stratosphere")
elif height > 50:print("mesosphere")
elif height > 100:print("space")
else:print("troposphere")
Tryheight=72onbothversions,whathappens?
0 10 20 30 40 50 60 70 80 90 100
troposphere stratosphere mesosphere spacekmaboveearth
Version3# incomplete version 3if height > 100:print("space")
elif height > 50:print("mesosphere")
elif height > 20:print("stratosphere")
Inthiscaseitispossiblethatnothingisprintedatall,when?
0 10 20 30 40 50 60 70 80 90 100
troposphere stratosphere mesosphere spacekmaboveearth
WhatHappensHere?# height is in kmif height > 100:print("space")
if height > 50:print("mesosphere")
if height > 20:print("stratosphere")
else:print("troposphere")
Tryheight=72
0 10 20 30 40 50 60 70 80 90 100
troposphere stratosphere mesosphere spacekmaboveearth
ThethenClauseor theelseClauseisExecuted
speed = 65limit = 70if speed <= limit:
print("Good job, safe driver!")else:
print("You owe $", speed/fine)
86Whatifwechangespeedto50?
Thebreak Statement• Thebreak statementterminatesthecurrentloopandresumesexecutionatthenextstatement
87
for letter in 'hollywood':if letter == 'l':
breakprint ('Current Letter :', letter)
Current Letter : hCurrent Letter : o
Thecontinue Statement• Thecontinue statementinPythonreturnsthecontroltothebeginningofthewhileloop.
88
for letter in 'hollywood':if letter == 'l':
continueprint ('Current Letter :', letter)
Current Letter : hCurrent Letter : oCurrent Letter : yCurrent Letter : wCurrent Letter : oCurrent Letter : oCurrent Letter : d