Top Banner
Lecture #03 – Introduction to Python and Programming, Control Flow Erkut Erdem, Aykut Erdem & Aydın Kaya // Fall 2017 BBM 101 Introduction to Programming I Monty Python and the Holy Grail (1975)
88

Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

Jul 31, 2018

Download

Documents

nguyennguyet
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

Lecture#03– IntroductiontoPythonandProgramming,ControlFlow

Erkut Erdem,AykutErdem&AydınKaya//Fall2017

BBM101IntroductiontoProgrammingI

MontyPythonandtheHolyGrail(1975)

Page 2: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

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)

Page 3: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

LectureOverview• Programminglanguages(PLs)

• IntroductiontoPythonandProgramming

• ControlFlow

3

Disclaimer:Muchofthematerialandslidesforthislecturewereborrowedfrom—E.Grimson,J.Guttag andC.Terman MIT6.0001class—RuthAnderson,MichaelErnstandBillHowe’sCSE140class—SwamiIyer’s Umass BostonCS110class

Page 4: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

LectureOverview• Programminglanguages(PLs)

• IntroductiontoPythonandProgramming

• ControlFlow

4

Page 5: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

ProgrammingLanguages

• Syntaxandsemantics

• DimensionsofaPL

• Programmingparadigms

Page 6: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

ProgrammingLanguages• Anartificiallanguagedesignedtoexpresscomputationsthatcanbeperformedbyamachine,particularlyacomputer.

• Canbeusedtocreateprogramsthatcontrolthebehaviorofamachine,toexpressalgorithmsprecisely,orasamodeofhumancommunication.

• e.g.,C,C++,Java,Python,Prolog,Haskell,Scala,etc..

Page 7: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

CreatingComputerPrograms• Eachprogramminglanguageprovidesasetofprimitiveoperations.

• Eachprogramminglanguageprovidesmechanismsforcombiningprimitivestoformmorecomplex,butlegal,expressions.

• Eachprogramminglanguageprovidesmechanismsfordeducingmeaningsorvaluesassociatedwithcomputationsorexpressions.

Page 8: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

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

Page 9: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

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

Page 10: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

AspectsofLanguages• Semantics– whatisthemeaningassociatedwithasyntacticallycorrectstringofsymbolswithnostaticsemanticerrors

– English– canbeambiguous• “Theysawthemanwiththetelescope.”

– Programming languages – alwayshasexactlyonemeaning• Butmeaning(orvalue)maynotbewhatprogrammerintended

Page 11: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

WhereCanThingsGoWrong?• Syntacticerrors

– Commonbuteasilycaughtbycomputer

• Staticsemanticerrors– Somelanguagescheckcarefullybeforerunning,otherscheck

whileinterpretingtheprogram– Ifnotcaught,behaviorofprogramisunpredictable

• Programsdon’thavesemanticerrors,butmeaningmaynotbewhatwasintended– Crashes(stopsrunning)– Runsforever– Producesananswer,butnotprogrammer’s intent

Page 12: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

OurGoal• Learnthesyntaxandsemanticsofaprogramminglanguage

• Learnhowtousethoseelementstotranslate“recipes”forsolvingaproblemintoaform thatthecomputercanusetodo theworkforus

• Computationalmodesofthoughtenableustouseasuiteofmethodstosolveproblems

Page 13: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

DimensionsofaProgrammingLanguageLow-levelvs.High-level

• Distinctionaccordingtothelevelofabstraction

• Inlow-levelprogramminglanguages(e.g.Assembly),thesetofinstructionsusedincomputationsareverysimple(nearlyatmachinelevel)

• Ahigh-levelprogramminglanguage(e.g.Python,C,Java)hasamuchricherandmorecomplexsetofprimitives.

Page 14: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

• Distinctionaccordingtotherangeofapplications

• Inageneralprogramminglanguage,thesetofprimitivessupportabroadrangeofapplications.

• Atargetedprogramminglanguage aimsataveryspecificsetofapplications.– e.g.,MATLAB(matrixlaboratory)isaprogramminglanguagespecificallydesignedfornumericalcomputing(matrixandvectoroperations)

DimensionsofaProgrammingLanguageGeneralvs.Targeted

Page 15: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

• Distinctionaccordingtohowthesourcecodeisexecuted

• Ininterpretedlanguages(e.g.LISP),thesourcecodeisexecuteddirectlyatruntime(bytheinterpreter).– Interpretercontroltheflowoftheprogrambygoingthrougheachoneoftheinstructions.

• Incompiledlanguages(e.g.C),thesourcecodefirstneedstobetranslatedintoanobjectcode(bythecompiler)beforetheexecution.

DimensionsofaProgrammingLanguageInterpretedvs.Compiled

Page 16: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

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.)

Page 17: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

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.)

Page 18: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

LectureOverview• Programminglanguages(PLs)

• IntroductiontoPythonandProgramming

• ControlFlow

18

Page 19: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

ProgramminginPython• Ourprogrammingenvironment– Pythonprogramminglanguage

– PyCharm,anintegrateddevelopmentenvironment(IDE)

– Terminal

19

Page 20: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

ProgramminginPython• ToprograminPython– Composeaprogrambytypingitintoafilenamed,say,helloworld.py

– Run(orexecute)theprogrambytypingpython helloworld.py intheterminalwindow

20

Editor(PyCharm)

compiler/interpreter(python)

helloworld.py Hello, World

Page 21: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

InputandOutput• Bird’s-eyeviewofaPythonprogram

– Inputtypes:command-linearguments,standardinput,fileinput

– Outputtypes:standardoutput,fileoutput,graphicaloutput,audiooutput

21

my_program.pyinput output

Page 22: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

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

Page 23: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

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

Page 24: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

1.Pythonislikeacalculator 2.Avariableisacontainer

4.Aprogramisarecipe3.Differenttypescannotbecompared

24

Page 25: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

1.PythonisLikeaCalculator

25

Page 26: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

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

Page 27: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

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

Page 28: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

AnotherEvaluationExample

(72 – 32)/(9.0 *5)(40)/(9.0 *5)40 /(9.0 *5)40 /(45.0)40 /45.0.888

28

Page 29: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

2.AVariableisaContainer

29

Avariableisanameassociatedwithadata-typevalue

Page 30: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

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

Page 31: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

ChangingExistingVariables(“re-binding”or“re-assigning”)

x = 2xy =yx = 5xy

• “=”inanassignmentisnot apromiseofeternalequality– Thisisdifferent thanthemathematicalmeaningof“=”

• Evaluatinganexpressiongivesanew(copyofa)number,ratherthanchanginganexistingone

2x

31

Page 32: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

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

Page 33: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

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

Page 34: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

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

Page 35: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

Stringsruler1 = '1'ruler2 = ruler1 + ' 2 ' + ruler1 ruler3 = ruler2 + ' 3 ' + ruler2 ruler4 = ruler3 + ' 4 ' + ruler3 print(ruler1)print(ruler2)print(ruler3)print(ruler4)

35

11211213121121312141213121

Page 36: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

3.DifferentTypescannotbeCompared

36

anInt = 2aString = "Hacettepe" anInt == aString # Error

Page 37: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

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

Page 38: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

OperationsBehavedifferentlyonDifferentTypes3.0 + 4.03 + 43 + 4.0"3" + "4" #Concatenation3 + "4" #Error3 + True #Error

Moral:Pythononlysometimes tellsyouwhenyoudosomethingthatdoesnotmakesense.

38

Page 39: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

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

Page 40: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

TypeConversion

float(15) 15.0int(15.0) 15int(15.5) 15int("15") 15str(15.5) 15.5float(15) / 4 3.75

40

Page 41: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

AProgramisaRecipe

41

Page 42: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

DesigntheAlgorithmBeforeCoding• Weshouldthink(designthealgorithm)beforecoding

• Algorithmicthinkingisthelogic.Also,calledproblemsolving

• Codingisthesyntax

• Makethisahabit

• Somestudentsdonotfollowthispracticeandtheygetchallengedinalltheircoursesandcareers!

42

Page 43: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

WhatisaProgram?• Aprogramisasequenceofinstructions

• Thecomputerexecutesoneaftertheother,asiftheyhadbeentypedtotheinterpreter

• Savingyourworkasaprogramisbetterthanre-typingfromscratch

43

x = 1y = 2x + yprint(x + y)print("The sum of", x, "and", y, "is", x+y)

Page 44: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

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

Page 45: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

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

Page 46: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

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

Page 47: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

1.Pythonislikeacalculator 2.Avariableisacontainer

4.Aprogramisarecipe3.Differenttypescannotbecompared

47

Page 48: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

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

}

Page 49: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

EvolutionofProgrammingLanguages

49

Page 50: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

The2017TopProgramming Languages

• https://spectrum.ieee.org/computing/software/the-2017-top-programming-languages 50

Page 51: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

51

http://carlche

o.com/startcoding

Page 52: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

LectureOverview• Programminglanguages(PLs)

• IntroductiontoPythonandProgramming

• ControlFlow

52

Page 53: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

Repeatingyourself

Makingdecisions

53

Page 54: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

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

Page 55: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

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

Page 56: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

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

Page 57: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

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

Page 58: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

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

Page 59: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

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

Page 60: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

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

Page 61: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

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

Page 62: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

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

Page 63: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

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

Page 64: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

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

Page 65: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

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

Page 66: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

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

Page 67: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

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

Page 68: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

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

Page 69: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

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

Page 70: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

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

Page 71: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

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)

Page 72: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

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

Page 73: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

MakingDecisions• Howdowecomputeabsolutevalue?

abs(5) = 5

abs(0) = 0

abs(-22) = 22

73

Page 74: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

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:

Page 75: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

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

Page 76: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

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

Page 77: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

AnotherifItisnotrequiredthatanythinghappens…

val = -10

if val < 0:print("negative value!")

77

Whathappenswhenval =5?

Page 78: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

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

Page 79: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

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

Page 80: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

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

Page 81: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

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

Page 82: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

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

Page 83: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

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

Page 84: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

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

Page 85: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

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

Page 86: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

ThethenClauseor theelseClauseisExecuted

speed = 65limit = 70if speed <= limit:

print("Good job, safe driver!")else:

print("You owe $", speed/fine)

86Whatifwechangespeedto50?

Page 87: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

Thebreak Statement• Thebreak statementterminatesthecurrentloopandresumesexecutionatthenextstatement

87

for letter in 'hollywood':if letter == 'l':

breakprint ('Current Letter :', letter)

Current Letter : hCurrent Letter : o

Page 88: Introduction to Programming I - Hacettepebbm101/lectures/lec3-python... · Lecture Overview •Programming languages (PLs) •Introduction to Python and Programming •Control Flow

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