Académique Documents
Professionnel Documents
Culture Documents
ES102
Lecture 4
print_lyrics(“engineer”)
print x
def addone(x):
x = x + 1
print “x + 1 = “, x + 1
a = 5
addone(a)
addone(a + 1)
def func(Y):
# Local scope
Z = X + Y
return Z
func(1)
def func(Y): def func(Y):
Z = X + Y Z = X + Y
return Z return Z
vs
X = 99 func(1)
func(1) X = 99
print “X = “, X print “X = “, X
def func(Y): def func(Y):
Z = X + Y Z = X + Y
return Z return Z
vs
X = 99 func(1) ERROR
func(1) X = 99
print “X = “, X print “X = “, X
● Variables = containers
Return values
● Functions can often return a value – e.g. math.sin(1.0)
def myfunction ( x ): def myfunction2 ( x ):
a = x + 1 return x + 1
return a
Val = myfunction(5)
Val = myfunction(5) print “Val = “,Val
print “Val = “,Val
def myfunction ( x ): def myfunction2 ( x ):
a = x + 1 return x + 1
return a
Val = myfunction(5)
Val = myfunction(5) print “Val = “,Val
print “Val = “,Val
● return statement returns the values after it
● If it is a mathematical expression, then the resulting value is returned
Return values
def myfunction ( x ):
return x + 1
Val = myfunction(myfunction(5)) + myfunction(6)
print “Val = “,Val
grade = “Y”
if score >= 40: Note the indentation again and
grade = “PASS” the colons
else:
grade = “NOT”
if...else
grade = “A”
The middle conditions are all elif
if score >= 90:
grade = “A”
elif score >= 80:
grade = “B”
elif score >= 70:
grade = “C”
else:
grade = “D”
grade = “A”
if testscore >= 90:
if labscore >= 90: Two different scores –
grade = “A+” testscore and labscore
else:
grade = “A”
elif testscore >= 80: Note the indentation –
if labscore >= 90 indicates the nesting
grade = “B+”
else:
grade = “B”
elif...
...
Dividing a number
● Suppose we want to read a number and then want to find
one of the following:
– “Number is divisible by 3 but not by 4”
– “Number is divisible by 4 and not 3”
– “Number is divisible by both 4 and 3”
– “Number is divisible by neither 3 nor 4”
result = 1
result = result * 2
result = result * 3
result = result * 4
….
Iteration
● Suppose we can do this:
– result = 1
– for each of the numbers i from 2,3,...,n
result = result * i
– Would we be done?
Iteration
● Suppose we can do this:
– result = 1
– while 2,3,...,n
result = result * i
● Corresponding python code
result = 1
i = 1
while i < 4:
result = result * i
i = i + 1
print “result =”, result
Iteration: while loop
result = 1
i = 1
while i < 4:
result = result * i
i = i + 1
print “result =”, result
i =1
result = 1
i < 4 condition
i = 1
while i < 4:
result = result * i
i = i + 1 result= result * i calculation
print “result =”, result
i = i + 1 change
i < 4
result= result * i i = i + 1
Iteration: while loop
result =1
i =1
result = 1
i = 1 condition
while i < 4: NO
i < 4 out of loop
result = result * i
i = i + 1 YES
print “result =”, result
result= result * i calculation
i = i + 1 change