[go: up one dir, main page]

0% found this document useful (0 votes)
21 views99 pages

ELE492 - Lecture 2 - 28-02-2023

1. Python is an interpreted programming language used for image processing. 2. The document provides information about Python versions, integrated development environments, and programming concepts in Python like variables, data types, and print statements. 3. Programming in Python involves writing code in files, running programs by calling the Python interpreter, and understanding basic concepts like input/output, variables, and print statements.

Uploaded by

ozllmtkn
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views99 pages

ELE492 - Lecture 2 - 28-02-2023

1. Python is an interpreted programming language used for image processing. 2. The document provides information about Python versions, integrated development environments, and programming concepts in Python like variables, data types, and print statements. 3. Programming in Python involves writing code in files, running programs by calling the Python interpreter, and understanding basic concepts like input/output, variables, and print statements.

Uploaded by

ozllmtkn
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 99

ELE 492: Image Processing

Assoc. Prof. Seniha Esen Yüksel

Lecture 2: Python

Hacettepe University
Department of Electrical and Electronics Engineering

** Course slides are the courtesy of Fual Akal, Erkut Erdem


and Aykut Erdem from the lecture notes of BBM 101
1
Text Books
• The Python Tutorial, available from the Python website.
– This is good for explaining the nuts and bolts of how Python
works.
• Introduction to Computation and Programming Using
Python, Second Edition, John V. Guttag, MIT Press, August
2016
• Think Python, 2nd edition
– Freely available online in HTML and PDF.
– Also available for purchase as a printed book, but don't buy
the first edition.
– This book introduces more conceptual material, motivating
computational thinking.
• There is an interactive version of “How to Think Like a
Computer Scientist” (the first edition of “Think Python”),
which lets you type and run Python code directly while
reading the book.

2
Python Version
• Whatever IDE you choose to work with,
always stick to Python version 3.6.5 or higher

• Always use this version to code your


assignments.

3
Integrated Development
Environment (IDE)
• There are many!

4
Programming in Python
• Our programming
environment
– Python programming
language
– PyCharm, an integrated
development environment
(IDE)
– Terminal

5
Programming in Python
• To program in Python
– Compose a program by typing it into a file named, say,
helloworld.py
– Run (or execute) the program by typing python
helloworld.py in the terminal window

compiler/
Editor
helloworld.py interpreter Hello, World
(PyCharm)
(python)

6
Input and Output
• Bird’s-eye view of a Python program

input my_program.py output

– Input types: command-line arguments, standard input, file


input
– Output types: standard output, file output, graphical
output, audio output

7
1. Python is like a calculator 2. A variable is a container

3. Different types cannot be compared 4. A program is a recipe

8
1. Python is Like a Calculator

9
You Type Expressions.
Python Computes Their Values.
• 5 Python has a natural and well-defined
set of precedence rules that fully
• 3+4 specify the order in which the operators
• 44/2 are applied in an expression
• 2**3 • For arithmetic operations, multiplication
and division are performed before addition
• 3*4+5*6 and subtraction

• (72 – 32) / 9 * 5 • When arithmetic operations have the same


precedence, they are left associative, with
the exception of the exponentiation
operator **, which is right associative
• We can use parentheses to override
precedence rules

10
An Expression is Evaluated
From the Inside Out
• How many expressions are in this Python code?
an expression values

(72 – 32) / 9.0 * 5 (72 – 32) / 9.0 * 5


(40) / 9.0 * 5
40 / 9.0 * 5
4.44 * 5
22.2
11
2. A Variable is a Container

A variable is a name associated


with a data-type value
12
Variables Hold Values
• Recall variables from algebra:
– Let x = 2 …
– Let y = x …

• To assign a variable, use “varname = expression”


pi = 3.14
pi
No output from an
var = 6*10**23 assignment statement
22 = x # Error!

• Not all variable names • Variable names must only be one word
are permitted! (as in no spaces)
• Variable names must be made up of only
letters, numbers, and underscore (_)
• Variable names cannot begin with a
number
13
Changing Existing Variables
(“re-binding” or “re-assigning”)
x = 2
x
y = 2
x
y
x = 5
x
y

• “=” in an assignment is not a promise of eternal equality


– This is different than the mathematical meaning of “=”

• Evaluating an expression gives a new (copy of a) number,


rather than changing an existing one

14
How an Assignment is Executed
1. Evaluate the right-hand side to a value
2. Store that value in the variable

x = 2 State of the computer: Printed output:

print(x) 2
x: 5
2
y = x 2
print(y) y: 2 3
z = x + 1 z: 3 5
print(z) 2
x = 5 3
print(x)
print(y) To visualize a program’s execution:
print(z) http://pythontutor.com 15
More Expressions: Conditionals
(value is True or False)
22 > 4 # condition, or conditional
22 < 4 # condition, or conditional
22 == 4 …
x = 100 # Assignment, not conditional!
22 = 4 # Error!
x >= 5
x >= 100
x >= 200 Numeric operators: +, *, **
not True Boolean operators: not, and, or
not (x >= 200) Mixed operators: <, >=, ==
3<4 and 5<6
4<3 or 5<6
temp = 72
water_is_liquid = (temp > 32 and temp < 212)
16
More Expressions: strings
• A string represents text
– 'Python'
– myString = "BBM 101-Introduction to Programming"
– ""

• We can specify tab, newline, backslash, and single quote characters using
escape sequences ’\t’, ’\n’, ’\\’, and ’\’’, respectively

Operations:
• Length:
– len(myString)

• Concatenation:
– "Hacettepe" + " " + ' University'

• Containment/searching:
– 'a' in myString
– "a" in myString

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

1
121
1213121
121312141213121

18
3. Different Types should not be Compared
anInt = 2
aString = "Hacettepe"
anInt == aString # Error

19
Types of Values

• Integers (int): -22, 0, 44


– Arithmetic is exact

• Real numbers (float, for “floating point”): 2.718,


3.1415
– Arithmetic is approximate, e.g., 6.022*10**23

• Strings (str): "I love Python", " "

• Truth values (bool, for “Boolean”):


True, False
George Boole
20
Operations Behave differently
on Different Types
3.0 + 4.0
3 + 4
3 + 4.0
"3" + "4" # Concatenation
3 + "4" # Error
3 + True # Error

Moral: Python only sometimes tells you when you


do something that does not make sense.

21
Operations on Different Types
Python 3.5 Python 2.x
15.0 / 4.0 3.75 3.75
15 / 4 3.75 3
15.0 / 4 3.75 3.75
15 / 4.0 3.75 3.75

15.0 // 4.0 3.0


Before Python version 3.5,
15 // 4 3 operand used to determine
the type of division.
15.0 // 4 3.0
15 // 4.0 3.0 / : Division
//: Integer Division

22
Type Conversion

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

23
A Program is a Recipe

24
Design the Algorithm Before Coding
• We should think (design the algorithm) before coding

• Algorithmic thinking is the logic. Also, called problem


solving

• Coding is the syntax

• Make this a habit

• Some students do not follow this practice and they get


challenged in all their courses and careers!

25
What is a Program?
• A program is a sequence of instructions

• The computer executes one after the other, as if they had been
typed to the interpreter

• Saving your work as a program is better than re-typing from


scratch

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

26
The print() Statement

• The print statement always prints one line


– The next print statement prints below that one

• Write 0 or more expressions after print, separated by


commas
– In the output, the values are separated by spaces

• Examples:
x = 1 3.1415
y = 2 2.718 1.618
print(3.1415)
22 21 20
print(2.718, 1.618) The sum of 1 and 2 is 3
print()
print(20 + 2, 7 * 3, 4 * 5) To avoid newline
print("The sum of", x, end="")
print(" and", y, "is", x+y)
27
Exercise: Convert Temperatures
• Make a temperature conversion chart as the following

• Fahrenheit to Centigrade, for Fahrenheit values of: -40, 0, 32, 68, 98.6, 212

• C = (F - 32) × 5/9

• Output:
Fahrenheit Centigrade
-40 -40.0
0 -17.7778
32 0.0
68 20.0
98.6 37.0
212 100.0

• You have created a Python program!

• (It doesn’t have to be this tedious, and it won’t be.)

28
Expressions, Statements, and Programs
• An expression evaluates to a value
3 + 4
pi * r**2

• A statement causes an effect


pi = 3.14159
print(pi)

• Expressions appear within other expressions and within statements


(fahr – 32) * (5.0 / 9)
print(pi * r**2)

• A statement may not appear within an expression


3 + print(pi) # Error!

• A program is made up of statements


– A program should do something or communicate information 29
Lecture Overview
• Control Flow

• Functions

30
Temperature Conversion Chart
Recall the exercise from the previous lecture

fahr = 30
cent = (fahr -32)/9.0*5
print(fahr, cent)
fahr = 40
cent = (fahr -32)/9.0*5
print(fahr, cent)
fahr = 50
cent = (fahr -32)/9.0*5
print(fahr, cent)
fahr = 60
cent = (fahr -32)/9.0*5 Output:
print(fahr, cent) 30 -1.11
fahr = 70 40 4.44
cent = (fahr -32)/9.0*5 50 10.0
print(fahr, cent) 60 15.55
Print("All done") 70 21.11
All done
31
Temperature Conversion Chart
A better way to repeat yourself:

loop variable or Colon is


for loop iteration variable A list required

Loop body
is indented for f in [30,40,50,60,70]:
Execute the body print(f, (f-32)/9.0*5)
5 times:
• once with f = 30 print("All done") Output:
• once with f = 40 30 -1.11
• once with f = 50 40 4.44
• once with f = 60
50 10.0
• once with f = 70
60 15.55
Indentation 70 21.11
is significant
All done 32
How a Loop is Executed:
Transformation Approach
Idea: convert a for loop into something we know how to execute

1. Evaluate the sequence expression


2. Write an assignment to the loop
variable, for each sequence
element
3. Write a copy of the loop after each
assignment
4. Execute the resulting statements
State of the
computer: Printed output:
i = 1
for i in [1,4,9]: print(i)
i: 9
1
4 1
print(i) i = 4
print(i)
4
i = 9 9
print(i)
33
How a Loop is Executed:
Direct Approach
1. Evaluate the sequence expression
2. While there are sequence
elements left:
a) Assign the loop variable to the next
remaining sequence element
b) Execute the loop body

State of the
Current location in list computer: Printed output:
for i in [1,4,9]:
i: 9
1
4 1
print(i)
4
9
34
The Body can be Multiple Statements

Execute whole body, then execute whole body again, etc.

for i in [3,4,5]: Output: NOT:


print("Start body") Start body Start body
loop body: 3 Start body
print(i) 3 statements 9 Start body
print(i*i) Start body 3
4 4
16 5
Start body 9
5 16
25 25

Convention: often use i or j as loop variable if values are integers


This is an exception to the rule that variable names should be
descriptive
35
Indentation in Loop is Significant
• Every statement in the body must have exactly the same indentation
• That’s how Python knows where the body ends
for i in [3,4,5]:
print("Start body")
Error! print(i)
print(i*i)

• Compare the results of these loops:


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")
36
The Body can be Multiple Statements

How many statements does this loop contain?

Output:
for i in [0,1]:
Outer 0
print("Outer", i) Inner 2
for j in [2,3]: Sum 2
Inner 3
print(" Inner", j) loop body:
“nested”
3 statements Sum 3
loop body: Outer 0
2 statements print(" Sum", i+j)
Outer 1
print("Outer", i) Inner 2
Sum 3
Inner 3
What is the output? Sum 4
Outer 1
37
Understand Loops Through the
Transformation Approach
Key idea:
1. Assign each sequence element to the loop variable
2. Duplicate the body

for i in [0,1]: i = 0 i = 0
print("Outer", i) print("Outer", i) print("Outer", i)
for j in [2,3]: for j in [2,3]: j = 2
print(" Inner", j) print(" Inner", j) print(" Inner", j)
i = 1 j = 3
print("Outer", i) print(" Inner", j)
for j in [2,3]: i = 1
print(" Inner", j) print("Outer", i)
for j in [2,3]:
print(" Inner", j)
38
Fix This Loop
# Goal: print 1, 2, 3, …, 48, 49, 50
for 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)

What does it actually print?


How can we change it to correct its output?

Moral: Watch out for edge conditions (beginning


or end of loop)
39
Some Fixes
# 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)

• Analyze each of the above

40
Test Your Understanding of Loops
Puzzle 1: Output:
for i in [0,1]: 0
print(i) 1
print(i) 1

Puzzle 2:
i = 5 (no output)
for i in []:
print(i) Reusing loop variable
Puzzle 3: (don’t do this!) Outer 0
Inner 2
for i in [0,1]: Inner 3
print("Outer", i) Outer 3
for i in [2,3]: outer Outer 1
inner loop Inner 2
print(" Inner", i) loop body Inner 3
print("Outer", i) body Outer 3 41
The Range Function

As an implicit list:
for i in range(5): The list
[0,1,2,3,4]
… body …
Upper limit
(exclusive)

range(5) = [0,1,2,3,4]
Lower limit
(inclusive)
range(1,5) = [1,2,3,4]
step (distance
between elements)
range(1,10,2) = [1,3,5,7,9]
42
Decomposing a List Computation

• To compute a value for a list:


– Compute a partial result for all but the last element
– Combine the partial result with the last element
Example: sum of a list:

[ 3, 1, 4, 1, 5, 9, 2, 6, 5 ]
List z

List y
sum(List a) = sum(List b) + 5
sum(List b) = sum(List c) + 6
List c …
List b sum(List y) = sum(List z) + 3
sum(empty list) = 0
List a 43
How to Process a List:
One Element at a Time
• A common pattern when processing a list:
result = initial_value # Sum of a list
for element in list: result = 0
result = updated result for element in mylist:
use result result = result + element
print result

• initial_value is a correct result for an empty list

• As each element is processed, result is a correct


result for a prefix of the list

• When all elements have been processed, result is a


correct result for the whole list
44
Some Loops
# Sum of a list of values, what values?
result = 0
for element in range(5): # [0,1,2,3,4]
result = result + element
print("The sum is: " + str(result)) The sum is: 10

# Sum of a list of values, what values?


result = 0
for element in range(5,1,-1): 5, 4, 3, 2
result = result + element The sum is: 14
print("The sum is:", result)

# Sum of a list of values, what values?


result = 0
for element in range(0,8,2): 0, 2, 4, 6
result = result + element
The sum is: 12
print("The sum is:", result)

# Sum of a list of values, what values?


result = 0 0, 1, 2, 3, 4
size = 5 When size = 5, the result is 10
for element in range(size):
result = result + element
print("When size = " + str(size) + ", the result is " + str(result))
45
Examples of List Processing
result = initial_value
for element in list:
• Product of a list: result = updated result
result = 1
for element in mylist:
result = result * element
• Maximum of a list: The first element of the
list (counting from zero)
result = mylist[0]
for element in mylist:
result = max(result, element)
• Approximate the value 3 by 1 + 2/3 + 4/9 + 8/27 + 16/81 + … =
(2/3)0 + (2/3)1 + (2/3)2 + (2/3)3 + … + (2/3)10
result = 0
for element in range(11):
result = result + (2.0/3.0)**element
46
Exercise with Loops
• Write a simple program to add values between two
given inputs a, b
• e.g., if a=5, b=9, it returns sum of (5+6+7+8+9)
• Hint: we did some ‘algorithmic thinking’ and
‘problem solving’ here! Notice this form of the
assignment statement!

a, b = 5, 9
total = 0
for x in range(a, b+1):
total += x
print(total)

47
Another Type of Loops – while
• The while loop is used for repeated
execution as long as an expression is true

n = 100
s = 0
counter = 1
while counter <= n:
s = s + counter
counter += 1

print("Sum of 1 until ” + str(n) + ": ” + str(s))

Sum of 1 until 100: 5050

48
Making Decisions
• How do we compute absolute value?

abs(5) = 5
abs(0) = 0
abs(-22) = 22

49
Absolute Value Solution
If the value is negative, negate it.
Otherwise, use the original value.

Another approach
val = -10 that does the same thing
without using result:
# calculate absolute value of val val = -10
if val < 0:
result = - val if val < 0:
else: print(- val)
result = val else:
print(val)
print(result)

In this example, result will always be assigned a value.


50
Absolute Value Solution
As with loops, a sequence of statements could
be used in place of a single statement inside an
if statement:
val = -10

# calculate absolute value of val


if val < 0:
result = - val
print("val is negative!")
print("I had to do extra work!")
else:
result = val
print("val is positive")
print(result)
51
Absolute Value Solution
What happens here?

val = 5

# calculate absolute value of val


if val < 0:
result = - val
print("val is negative!")
else:
for i in range(val):
print("val is positive!")
result = val
print(result)

52
Another if
It is not required that anything happens…

val = -10

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

What happens when val = 5?

53
The if Body can be Any Statements
differently! but more efficient!
Written differently,
# height is in km
# height is in km
if height > 100:
Execution getsif hereheight
only 50:
> 100:
then print("space")
clause iffalse
height > 100:
print("space")
if “height > 100” is
else:
elifprint("space")
height > 50:
if height > 50: Execution gets here only
else:
print("mesosphere")
t print("mesosphere") if “height > 100” is false
“heightprint("mesosphere")
AND elif height
> 50” is true> 20:
else else:
else:
print("stratosphere")
clause if height > 20:
if height > 20:
else:
t print("stratosphere")
f print("stratosphere")
print("troposphere")
else:
else:
f print("troposphere")
print("troposphere")
troposphere stratosphere mesosphere space
km
above
0 10 20 30 40 50 60 70 80 90 100 54
earth
Version 1
# height is in km
if height > 100:
then Execution gets here only
print("space")
clause if “height <= 100” is true
else:
if height > 50: Execution gets here only
t print("mesosphere") if “height <= 100” is true
AND “height > 50” is true
else else:
clause if height > 20:
t print("stratosphere")
e
else:
e print("troposphere")

troposphere stratosphere mesosphere space


km
above
0 10 20 30 40 50 60 70 80 90 100 earth
Version 1
# height is in km
if height > 100:
print("space")
else:
if height > 50:
print("mesosphere")
else:
if height > 20:
print("stratosphere")
else:
print("troposphere")

troposphere stratosphere mesosphere space


km
above
0 10 20 30 40 50 60 70 80 90 100 earth
Version 2
if height > 50:
if height > 100:
print("space")
else:
print("mesosphere")
else:
if height > 20:
print("stratosphere")
else:
print("troposphere")

troposphere stratosphere mesosphere space


km
above
0 10 20 30 40 50 60 70 80 90 100 earth
Version 3
if height > 100:
print("space")
elif height > 50:
print("mesosphere")
elif height > 20:
print("stratosphere")
else:
print("troposphere")

ONE of the print statements is guaranteed to execute:


whichever condition it encounters first that is true
troposphere stratosphere mesosphere space
km
above
0 10 20 30 40 50 60 70 80 90 100 earth
Order Matters
# version 3 # broken version 3
if height > 100: if height > 20:
print("space") print("stratosphere")
elif height > 50: elif height > 50:
print("mesosphere") print("mesosphere")
elif height > 20: elif height > 100:
print("stratosphere") print("space")
else: else:
print("troposphere") print("troposphere")

Try height = 72 on both versions, what happens?


troposphere stratosphere mesosphere space
km
above
0 10 20 30 40 50 60 70 80 90 100 earth
Version 3
# incomplete version 3
if height > 100:
print("space")
elif height > 50:
print("mesosphere")
elif height > 20:
print("stratosphere")

In this case it is possible that nothing is printed at all, when?

troposphere stratosphere mesosphere space


km
above
0 10 20 30 40 50 60 70 80 90 100 earth
What Happens Here?
# height is in km
if height > 100:
print("space")
if height > 50:
print("mesosphere")
if height > 20:
print("stratosphere")
else:
print("troposphere")

Try height = 72
troposphere stratosphere mesosphere space
km
above
0 10 20 30 40 50 60 70 80 90 100 earth
divisorpattern.py: Accept integer command-line argument
n. Write to standard output an n-by-n table with an asterisk in
row i and column j if either i divides j or j divides i.
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)

62
The break Statement
• The break statement terminates the current
loop and resumes execution at the next
statement
for letter in 'hollywood':
if letter == 'l':
break
print ('Current Letter :', letter)

Current Letter : h
Current Letter : o

63
The continue Statement
• The continue statement in Python returns
the control to the beginning of the while loop.

for letter in 'hollywood':


if letter == 'l':
continue
print ('Current Letter :', letter)

Current Letter : h
Current Letter : o
Current Letter : y
Current Letter : w
Current Letter : o
Current Letter : o
Current Letter : d
64
Lecture Overview
• Control Flow

• Functions

65
Functions
• In math, you use functions: sine, cosine, …
• In math, you define functions: f(x) = x2 + 2x + 1

• A function packages up and names a computation


• Enables re-use of the computation (generalization)
• Don’t Repeat Yourself (DRY principle)
• Shorter, easier to understand, less error-prone

• Python lets you use and define functions


• We have already seen some Python functions:
– len, float, int, str, range

66
Using (“calling”) a Function
len("hello") len("")
round(2.718) round(3.14)
pow(2, 3) range(1, 5)
math.sin(0) math.sin(math.pi / 2)

• Some need no input:


random.random()

• All produce output

67
A Function is a Machine
• You give it input
• It produces a result (output)

2 0 100
x x x

2x + 1 2x + 1 2x + 1

5 1 201

In math: func(x) = 2x + 1
68
Creating a Function
Define the machine, x
including the input and the result
2x + 1
Name of the function.
Like “y = 5” for a variable

Keyword that means: Input variable name,


I am defining a function or “formal parameter”

def dbl_plus(x):
return 2*x + 1
Keyword that means: Return expression
This is the result (part of the return statement)
69
More Function Examples
Define the machine, including the input and the result
def square(x): def print_hello():
return x * x print("Hello, world")
No return statement
def fahr_to_cent(fahr): Returns the value None
return (fahr – 32) / 9.0 * 5 Are also called ‘procedures’
def print_fahr_to_cent(fahr):
def cent_to_fahr(cent): result = fahr_to_cent(fahr)
result = cent / 5.0 * 9 + 32 print(result)
return result
What is the result of:
def abs(x): x = 42
if x < 0: square(3) + square(4)
return – x print(x)
else: boiling = fahr_to_cent(212)
return x cold = cent_to_fahr(-40)
print(result)
print(abs(-22))
print(print_fahr_to_cent(32))
70
Python Interpreter
• An expression evaluates to a value
– Which can be used by the containing expression or statement

• print("test") statement writes text to the screen

• The Python interpreter (command shell) reads statements


and expressions, then executes them

• If the interpreter executes an expression, it prints its value

• In a program, evaluating an expression does not print it

• In a program, printing an expression does not permit it to


be used elsewhere

71
An example
def lyrics():
print("The very first line")
print(lyrics())

The very first line


None

72
How Python Executes a Function Call
Function def square(x): 1 + square(3 + 4)
definition return x * x Function call or
Formal
Actual function invocation
parameter
Current expression: argument
(a variable)
1 + square(3 + 4) Variables:
1 + square(7) return x * x x: 7
return 7 * x
evaluate this expression
return 7 * 7
1 + 49 return 49
50
1. Evaluate the argument (at the call site)
2. Assign the formal parameter name to the argument’s value
– A new variable, not reuse of any existing variable of the same name
3. Evaluate the statements in the body one by one
4. At a return statement:
– Remember the value of the expression
– Formal parameter variable disappears – exists only during the call!
– The call expression evaluates to the return value 73
Example of Function Invocation
def square(x):
return x * x
Variables:
square(3) + square(4) (none)
return x * x x: 3
return 3 * x x: 3
return 3 * 3 x: 3
return 9 x: 3
9 + square(4) (none)
return x * x x: 4
return 4 * x x: 4
return 4 * 4 x: 4
return 16 x: 4
9 + 16 (none)
25 (none)

74
Expression with Nested Function Invocations:
Only One Executes at a Time
def fahr_to_cent(fahr):
return (fahr – 32) / 9.0 * 5

def cent_to_fahr(cent):
return cent / 5.0 * 9 + 32
Variables:
fahr_to_cent(cent_to_fahr(20)) (none)
return cent / 5.0 * 9 + 32 cent: 20
return 20 / 5.0 * 9 + 32 cent: 20
return 68 cent: 20
fahr_to_cent(68) (none)
return (fahr – 32) / 9.0 * 5 fahr: 68
return (68 – 32) / 9.0 * 5 fahr: 68
return 20 fahr: 68
20 (none)
75
Expression with Nested Function Invocations:
Only One Executes at a Time
def square(x):
return x * x
Variables:
square(square(3)) (none)
return x * x x=3
return 3 * x x=3
return 3 * 3 x=3
return 9 x=3
square(9) (none)
return x * x x=9
return 9 * x x=9
return 9 * 9 x=9
return 81 x=9
81 (none)

76
Function that Invokes Another Function:
Both Function Invocations are Active
import math
def square(z):
return z*z
def hypoten_use(x, y):
return math.sqrt(square(x) + square(y))
Variables:
hypoten_use(3, 4) (none)
return math.sqrt(square(x) + square(y)) x:3 y:4
return math.sqrt(square(3) + square(y)) x:3 y:4
return z*z z: 3
return 3*3 z: 3
return 9 z: 3
return math.sqrt(9 + square(y)) x: 3 y:4
return math.sqrt(9 + square(4)) x: 3 y:4
return z*z z: 4
return 4*4 z: 4
return 16 z: 4
return math.sqrt(9 + 16) x: 3 y:4
return math.sqrt(25) x: 3 y:4
return 5 x:3 y:4
5 (none) 77
Shadowing of Formal Variable Names
import math
def square(x): Same formal
return x*x parameter name
def hypotenuse(x, y):
return math.sqrt(square(x) + square(y))
Variables:
hypotenuse(3, 4) (none)
Formal
return math.sqrt(square(x) + square(y)) x: 3 y:4 parameter is a
return math.sqrt(square(3) + square(y)) x: 3 y:4 new variable
return x*x x: 3
return 3*3 x: 3
return 9 x: 3
return math.sqrt(9 + square(y)) x: 3 y:4
return math.sqrt(9 + square(4)) x: 3 y:4
return x*x x: 4
return 4*4 x: 4
return 16 x: 4
return math.sqrt(9 + 16) x: 3 y:4
return math.sqrt(25) x: 3 y:4
return 5 x:3 y:4
5 (none) 78
Shadowing of Formal Variable Names
import math
def square(x): Same diagram, with
return x*x variable scopes or
def hypotenuse(x, y): environment frames
return math.sqrt(square(x) + square(y)) shown explicitly
Variables:
hypotenuse(3, 4) (none) hypotenuse()
return math.sqrt(square(x) + square(y)) x:3 y:4
return math.sqrt(square(3) + square(y)) square() x:3 y:4
return x*x x: 3 x:3 y:4
return 3*3 x: 3 x:3 y:4
return 9 x: 3 x:3 y:4
return math.sqrt(9 + square(y)) x:3 y:4
return math.sqrt(9 + square(4)) square() x:3 y:4
return x*x x: 4 x:3 y:4
return 4*4 x: 4 x:3 y:4
return 16 x: 4 x:3 y:4
return math.sqrt(9 + 16) x:3 y:4
return math.sqrt(25) x:3 y:4
return 5 x:3 y:4
5 (none) 79
In a Function Body, Assignment Creates a
Temporary Variable (like the formal parameter)
stored = 0
def store_it(arg):
stored = arg
return stored
y = store_it(22)
print(y)
print(stored) Variables:
Global or
Show evaluation of the starred expressions: top level
y = store_it(22) store_it() stored: 0
stored = arg; return stored arg: 22 stored: 0
stored = 22; return stored arg: 22 stored: 0
return stored arg: 22 stored: 22 stored: 0
return 22 arg: 22 stored: 22 stored: 0 y: 22
y = 22 stored: 0 y: 22
print(stored) stored: 0 y: 22
print(0) 80
How to Look Up a Variable
Idea: find the nearest variable of the given name
1. Check whether the variable is defined in the local scope
2. … check any intermediate scopes …
3. Check whether the variable is defined in the global scope
If a local and a global variable have the same name, the global
variable is inaccessible (“shadowed”)
This is confusing; try to avoid such shadowing
x = 22 def lookup():
stored = 100 x = 42
def lookup(): return stored + x
x = 42 x = 22
return stored + x stored = 100 What happens if
lookup() lookup() we define stored
x = 5 x = 5 after lookup()?
stored = 200 stored = 200
lookup() lookup()

81
Local Variables Exist Only while the
Function is Executing
def cent_to_fahr(cent):
result = cent / 5.0 * 9 + 32
return result

tempf = cent_to_fahr(15)
print(result)

82
Use Only the Local and the Global Scope

myvar = 1

def outer():
myvar = 1000
return inner()

def inner():
return myvar

print(outer())

83
Abstraction
• Abstraction = ignore some details

• Generalization = become usable in more contexts

• Abstraction over computations:


– functional abstraction, a.k.a. procedural abstraction

• As long as you know what the function means,


you don’t care how it computes that value
– You don’t care about the implementation
(the function body)

84
Defining Absolute Value
def abs(x): def abs(x):
if val < 0: if val < 0:
return -1 * val result = - val
else: else:
return 1 * val result = val
return result

def abs(x):
if val < 0: def abs(x):
return - val return math.sqrt(x*x)
else:
return val

They all perform the same task.


Their implementations are different though.
85
Defining Round (for positive numbers)
def round(x):
return int(x+0.5)

def round(x):
fraction = x - int(x)
if fraction >= .5:
return int(x) + 1
else:
return int(x)

86
Each Variable Should Represent One Thing
def atm_to_mbar(pressure): # Best
return pressure * 1013.25 def atm_to_mmHg(pressure):
in_mbar = atm_to_mbar(pressure)
def mbar_to_mmHg(pressure): in_mmHg = mbar_to_mmHg(in_mbar)
return pressure * 0.75006 return in_mmHg
print(atm_to_mmHg(1.2))
# Confusing
pressure = 1.2 # in atmospheres
pressure = atm_to_mbar(pressure) Corollary: Each variable should contain
pressure = mbar_to_mmHg(pressure) values of only one type
print(pressure)
# Legal, but confusing: don’t do this!
# Better
x = 3
in_atm = 1.2

in_mbar = atm_to_mbar(in_atm)
x = "hello"
in_mmHg = mbar_to_mmHg(in_mbar)

print(in_mmHg)
x = [3, 1, 4, 1, 5]

If you use a descriptive variable name, you are unlikely to make these mistakes
87
Exercises
def cent_to_fahr(c): def c_to_f(c):
print(cent / 5.0 * 9 + 32) print("c_to_f")
return c / 5.0 * 9 + 32
print(cent_to_fahr(20))
def make_message(temp):
print("make_message")
def myfunc(n): return ("The temperature is "
total = 0 + str(temp))
for i in range(n):
total = total + i for tempc in [-40,0,37]:
return total tempf = c_to_f(tempc)
message = make_message(tempf)
print(myfunc(4)) print(message)

float(7) abs(-20 - 2) + 20

88
What Does This Print?
def myfunc(n):
total = 0
for i in range(n):
total = total + i
return total

print(myfunc(4))
6

89
What Does This Print?
def c_to_f(c):
print("c_to_f")
return c / 5.0 * 9 + 32

def make_message(temp):
c_to_f
print("make_message")
make_message
return "The temperature is " + str(temp)
The temperature is -40.0
c_to_f
for tempc in [-40,0,37]:
make_message
tempf = c_to_f(tempc)
The temperature is 32.0
message = make_message(tempf)
c_to_f
print(message)
make_message
The temperature is 98.6

90
Decomposing a Problem
• Breaking down a program into functions is the
fundamental activity of programming!

• How do you decide when to use a function?


– One rule: DRY (Don’t Repeat Yourself)
– Whenever you are tempted to copy and paste
code, don’t!

• Now, how do you design a function?

91
Review: How to Evaluate a Function Call
1. Evaluate the function and its arguments to values
– If the function value is not a function, execution terminates with an error
2. Create a new stack frame
– The parent frame is the one where the function is defined
– A frame has bindings from variables to values
– Looking up a variable starts here
• Proceeds to the next older frame if no match here
• The oldest frame is the “global” frame
• All the frames together are called the “environment”
– Assignments happen here
3. Assign the actual argument values to the formal parameter variable
– In the new stack frame
4. Evaluate the body
– At a return statement, remember the value and exit
– If at end of the body, return None
5. Remove the stack frame
6. The call evaluates to the returned value
92
Functions are Values:
The Function can be an Expression
import math

def double(x):
return 2*x
print(double)
myfns = [math.sqrt, int, double, math.cos]
myfns[1](3.14)
myfns[2](3.14)
myfns[3](3.14)

def doubler():
return double
doubler()(2.718)

93
Nested Scopes
• In Python, one can always determine the scope of a name by
looking at the program text.
– static or lexical scoping
def f(x):
def g():
x = "abc"
print("x =", x) x = 4
def h(): z = 4
z = x x = abc
print("z =", z)
x = x+1 x = 4
print("x =", x) x = 3
h() z = <function f.<locals>.g at
g() 0x7f06d7fa2ea0>
print("x =", x) x = abc
return g
x = 3
z = f(x)
print("x =", x)
print("z =", z)
z() 94
Anonymous (lambda) Functions
• Anonymous functions are also called lambda functions in
Python because instead of declaring them with the standard
def keyword, you use the lambda keyword.

lambda x: x*2 is the lambda function.


double = lambda x: x*2
x is the argument
double(5)
x*2 is the expression or instruction that
gets evaluated and returned.

lambda x, y: x + y;

is equal to
You use lambda functions when you require a
def sum(x, y): nameless function for a short period of time,
return x+y and that is created at runtime.

95
Two Types of Documentation
1. Documentation for users/clients/callers
– Document the purpose or meaning or abstraction that the function
represents
– Tells what the function does
– Should be written for every function
2. Documentation for programmers who are reading the code
– Document the implementation – specific code choices
– Tells how the function does it
– Only necessary for tricky or interesting bits of the code
For users: a string as the first
element of the function body For programmers:
called arbitrary text after #
def square(x):
docstring """Returns the square of its argument."""
# "x*x" can be more precise than "x**2"
return x*x
96
Multi-line Strings
• New way to write a string – surrounded by three
quotes instead of just one
– "hello"
– 'hello'
– """hello"""
– '''hello'''

• Any of these works for a documentation string

• Triple-quote version:
– can include newlines (carriage returns),
so the string can span multiple lines
– can include quotation marks

97
Don’t Write Useless Comments
• Comments should give information that is not
apparent from the code

• Here is a counter-productive comment that


merely clutters the code, which makes the
code harder to read:

# increment the value of x


x = x + 1

98
Where to Write Comments
• By convention, write a comment above the code that it describes
(or, more rarely, on the same line)
– First, a reader sees the English intuition or explanation, then the
possibly-confusing code

# The following code is adapted from


# "Introduction to Algorithms", by Cormen et al.,
# section 14.22.
while (n > i):
...
• A comment may appear anywhere in your program, including at the
end of a line:

x = y + x # a comment about this line

• For a line that starts with #, indentation must be consistent with


surrounding code

99

You might also like