ELE492 - Lecture 2 - 28-02-2023
ELE492 - Lecture 2 - 28-02-2023
Lecture 2: Python
Hacettepe University
Department of Electrical and Electronics Engineering
2
Python Version
• Whatever IDE you choose to work with,
always stick to Python version 3.6.5 or higher
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
7
1. Python is like a calculator 2. A variable is a container
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
10
An Expression is Evaluated
From the Inside Out
• How many expressions are in this Python code?
an expression values
• 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
14
How an Assignment is Executed
1. Evaluate the right-hand side to a value
2. Store that value in the variable
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
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
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
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
x = 1
y = 2
x + y
print(x + y)
print("The sum of", x, "and", y, "is", x+y)
26
The print() Statement
• 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
28
Expressions, Statements, and Programs
• An expression evaluates to a value
3 + 4
pi * r**2
• 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 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
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
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
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)
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
[ 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
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
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)
val = 5
52
Another if
It is not required that anything happens…
val = -10
if val < 0:
print("negative value!")
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")
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.
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
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)
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
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
71
An example
def lyrics():
print("The very first line")
print(lyrics())
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
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
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!
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, 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'''
• 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
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
99