Advanced Programming 2024 Lecture 2a
Advanced Programming 2024 Lecture 2a
Simon Scheidegger
Department of Economics, University of Lausanne, Switzerland
1 / 69
Roadmap
1 / 69
Recall — What does a Computer do?
▶ Fundamentally:
▶ performs calculations:
several billion calculations per second even on a Laptop!
▶ remembers results:
∼ terabytes of storage even on a Laptop!
▶ What kinds of calculations?
▶ built-in to the language (basic types: additions, substraction,....)
▶ Some calculations that you define as the programmer (built on top of the basic
operations).
2 / 69
Algorithm: A Basic Example – compute sqrt(x)
3 / 69
Recall — Algorithms
4 / 69
Comuters => Machines
5 / 69
Recall — a computer
6 / 69
Basics: von Neumann Architecture
https://computing.llnl.gov/tutorials/parallel_comp
▶ Virtually all computers have followed this basic design. Comprised of four
main components: Memory, Control Unit, Arithmetic Logic Unit,
Input/Output.
▶ Read/write, random access memory is used to store both program
instructions and data:
▶ Program instructions are coded data which tell the computer to
do something.
▶ Data is simply information to be used by the program.
▶ Control unit
▶ fetches instructions/data from memory, decodes the instructions
and then sequentially coordinates operations to accomplish the
programmed task.
▶ Arithmetic unit
▶ performs basic arithmetic operations.
▶ Input/Output
▶ interface to the human operator.
7 / 69
A (Python) Program
8 / 69
Recall — Some features
9 / 69
Recall — Syntax and Design
▶ One nice feature of Python is its elegant syntax — we’ll see many examples later
on.
▶ Elegant code might sound superfluous but in fact it’s highly beneficial because it
makes the syntax easy to read and easy to remember.
▶ Remembering how to read from files, sort dictionaries and other such routine
tasks means that you don’t need to break your flow in order to hunt down correct
syntax.
▶ Closely related to elegant syntax is elegant design.
▶ Features like iterators, generators, list comprehensions, etc. make Python highly
expressive, allowing you to get more done with less code.
10 / 69
1. Python Basics
11 / 69
Python Setup
12 / 69
Python Basics I
13 / 69
Python Basics II
14 / 69
Objects
15 / 69
Scalar Objects
16 / 69
Action required: Type conversions
>>> float(10)
10.0
>>> int(10.9)
10
17 / 69
Print to the Terminal
demo/example1a.py
>>> 10 + 2
12
>>> print(10+2)
12
a = 3+4
print('no printout so far')
print('here we go')
print(a)
18 / 69
Action Required
a = 3
b = 2
sum = a + b
▶ Run demo/example1a.py: print('no printout of the result so far')
python example1a.py
a = 3
▶ Run demo/example1b.py:
b = 2
python example1b.py
sum = a + b
print('no printout of the result so far')
print("here we go with the result")
print(sum)
19 / 69
Create Expressions
▶ Combine objects and operators to form expressions
▶ An expression has a value, which has a type
▶ syntax for a simple expression:
20 / 69
Summary: Numeric Operators
▶ Parentheses are used to tell Python to do these operations first
▶ Operator precedence without parentheses
▶ “+’‘ and “-” are executed left to right, as appear in expression
21 / 69
Order of Expressions
22 / 69
Assignments
>>> pi = 3.1415
>>> pi
3.1415
23 / 69
Expressions
demo/example2.py
>>> pi = 3.14159
>>> radius = 2.0
>>> area = pi * (radius**2)
24 / 69
Programming logic vs. math logic
>>> pi = 3.14159
>>> radius = 2.0
>>> area = pi * (radius**2)
>>> radius = radius + 1
>>> radius
3.0
▶ → “=” is an assignment.
▶ → It strictly means “the expression on the right evaluated to a value on the left.”
25 / 69
Change Assignments
demo/example2b.py
▶ You can re-assign (re-bind) variable names using new assignment statements.
▶ Previous value may still stored in memory but lost the handle for it.
▶ The value for area does not change until you tell the computer to do the
calculation again.
>>> pi = 3.14159
>>> radius = 2.0
>>> area = pi * (radius**2)
>>> radius = radius + 1
26 / 69
Augmented Assignments
demo/example2c.py
27 / 69
Another helpful online tool
The Online Python Tutor is a free tool to visualize the execution of programs
step-by-step.
Feel free to use it for the course exercises and your own code:
http://pythontutor.com/visualize.html
28 / 69
Object: Characters, Strings
demo/example3.py
29 / 69
Input and Output
demo/example4.py
x = 666
print(x)
x_str = str(x) #Cast the number to a string
print("my favorite number is", x, ".", "x =", x) # use commas -> different objects
print("my favorite number is " + x_str + ". " + "x = " + x_str) # one big string object
30 / 69
Interactive Program: Input and Output (II)
demo/example5.py
31 / 69
Add tests to the Code: Comparison operators
▶ Assume i and j are variable names
▶ Comparisons shown below evaluate to a Boolean (logical)
▶ i > j
▶ i >= j
▶ i < j
▶ i <= j
▶ i == j → equality test, True if i is the same as j
▶ i != j → inequality test, True if i is NOT the same as j
▶ These tests work on int, float, string
>>> i = 3
>>> j = 5
>>> j < i
False
32 / 69
Testing: Logical operations
>>> a='true'
>>> b='true'
>>>a==b
Out[17]: True
>>>a!=b
Out[18]: False
33 / 69
2. Control flow: Branching and Loops
34 / 69
Control flow in the real world
35 / 69
Branching
36 / 69
Branching: if-else statements
if-elif-else statements:
if x < 0:
print("x is less than zero")
if x < 0:
print("x is less than zero")
else:
print("x is greater or equal zero")
if x < 0:
print("x is less than zero")
elif x > 0:
print ("x is greater than zero")
else:
print ("x is zero")
37 / 69
Indentation matters in Python to denote blocks of
code
demo/example6.py
38 / 69
if-else branching in general
39 / 69
Visualized: One-way if-statements
Start
Start
False
False radius >= 0?
boolean-expression
True
True
area = radius*radius*3.14159;
Statement(s) print(”The area for the circle of radius is”, area)
Stop
Stop
40 / 69
Visualized: Two-way if-statements
if boolean-expression:
statement(s)-for-the-true-case
else:
statement(s)-for-the-false-case
Start
True False
boolean-expression
Statement(s) for the true case Statement(s) for the false case
End
41 / 69
Multiple alternative if-statements
42 / 69
Flowchart
Start
false
score ≥ 90
false
true score ≥ 80
grade = ’A’
false
true score ≥ 70
grade = ’B’
false
true score ≥ 60
grade = ’C’
true
grade = ’D’
grade = ’F’
End
43 / 69
Another Example
demo/example6a.py
44 / 69
Another Example
demo/example6c.py
45 / 69
Control flow: while loop
demo/example7.py
46 / 69
While loop — iteration
47 / 69
Control flow: while loop in general
while <condition>:
<expression>
<expression>
...
48 / 69
Loops — the Motivation
49 / 69
Opening Problem
50 / 69
Control flow: for loops I
demo/example8.py
i = 0
while i < 10:
print(i)
i = i+1
▶ Shortcut for the for loop
for i in range(10):
print(i)
51 / 69
Control flow: for loops II
demo/example8.py
sum = 0
for i in range(5,7):
sum += i
print(sum) demo/example8a.py
demo/example8b.py
sum = 0
for i in range(40,50,2):
sum += i
print(sum)
52 / 69
Control flow: for loops III
demo/example8.py
53 / 69
Example
demo/example9.py
for i in range(5):
print(i)
lst = ["Suzuki","Kawasaki","Aprilia","Ducati"]
# use enumerate below!!!
# for i in range(len(lst)):
# print(i,lst[i])
for (i,item) in enumerate(lst):
print(i,item)
54 / 69
Stop within a loop — break statement
▶ If you want to immediately exit a loop → break
▶ It skips remaining expressions in the code block.
▶ Note: it exits only innermost loop.
while <condition_1>:
while <condition_2>:
<expression_a>
break
<expression_b>
<expression_c>
55 / 69
break — an example
demo/example10.py
var = 10
while var > 0:
print('Current variable value :', var)
var = var -1
if var == 5:
break
56 / 69
3. String Manipulation
57 / 69
Strings → Sequences of Characters
Square brackets are used to perform indexing into a string to get the value at a certain
index/position.
s = ''abcd''
58 / 69
Mutable vs. Immutable types
▶ Mutable types
▶ Can change their contents / members
▶ lists, dicts, user-defined types
▶ Immutable types
▶ Cannot change their contents / members
▶ most built-in types (int, float, bool, str, tuple)
59 / 69
Recap: Strings and Loops
demo/example11.py
The two code snippets below do the same thing: they loop over the characters in the
string.
s = "mickey"
for index in range(len(s)):
if s[index] == 'i' or s[index] == 'y':
print("There is an i or y")
for char in s:
if char == 'i' or char == 'y':
print("There is an i or y")
60 / 69
4. Examples
61 / 69
Example: Guess and Check
demo/example12.py
cube = 8
for guess in range(abs(cube)+1):
if guess**3 >= abs(cube):
break
if guess**3 != abs(cube):
print(cube, 'is not a perfect cube')
else:
if cube < 0:
guess = -guess
print('Cube root of '+str(cube)+' is '+str(guess))
62 / 69
Approximate Solutions
63 / 69
Recall — IEEE Floating Point Representation
64 / 69
An approximate solution
demo/example13.py
cube = 27.8
epsilon = 0.1
guess = 0.0
increment = 0.01
num_guesses = 0
# look for close enough answer and make sure
# didn't accidentally skip the close enough bound and thus overshoot
while abs(guess**3 - cube) >= epsilon and guess <= cube:
guess += increment
num_guesses += 1
print('num_guesses =', num_guesses)
if abs(guess**3 - cube) >= epsilon:
print('Failed on cube root of', cube, "with these parameters.")
else:
print(guess, 'is close to the cube root of', cube)
65 / 69
Another example: Bisection
Binary search algorithm - https://en.wikipedia.org/wiki/Binary_search_algorithm
66 / 69
Bisection applied to the cube root
demo/example14.py
cube = 27.8
# won't work with x < 1 because initial upper bound is less than ans
#cube = 0.25
epsilon = 0.01
num_guesses = 0
low = 0
high = cube
guess = (high + low)/2.0
while abs(guess**3 - cube) >= epsilon:
if guess**3 < cube:
# look only in upper half search space
low = guess
else:
# look only in lower half search space
high = guess
# next guess is halfway in search space
guess = (high + low)/2.0
num_guesses += 1
print('num_guesses =', num_guesses)
print(guess, 'is close to the cube root of', cube)
67 / 69
Bisection applied to the cube root
68 / 69
Summary → GIT next
69 / 69