Week 4
Week 4
February 9, 2024
1 MATH0011 Python L3
• Please do the Python experience survey on Moodle.
• Slides are on Moodle.
• survey is just about what programming experience you had before taking 0011. It’s really
useful for me to know that.
[ ]: def f(x):
print(x+1)
def g(x):
return x+2
f(1) # what will happen?
f(1) + g(1) # what will happen?
g(1) + g(1) # what will happen?
[ ]: def f(a):
for i in range(100):
if a[i] > a[i+1]:
return 0
1
else:
return 1
Most common errors - print vs return (“return print(x + y)”) - returning in a loop stops the loop,
always - function execution stops when a return is encountered, no exceptions - returning too early
inside a loop - misunderstanding the memory model, = isn’t equality
There are some extremely common and fundamental misunderstandings that people make. It’s not
just exams, these are fundamental probramming errors - but exams often test them.
2023 Q1(b) - make sure you completely understand this. Run the code yourself in a notebook.
Your CoCalc account will not go away. You can always check your answers.
Even if the return is in a loop!
You should immediately recognise that code like this can’t possibly be correct. The function
returns a value when i=0, always. Other values of i are never even considered. The for loop is
pointless - something MUST be wrong. Most likely, the second for loop should appear after the
loop completed.
[ ]: import numpy as np
x = np.array([1, 2, 3])
y = np.array([3, 2, 1])
z = np.array([2, 2, 2])
a = [x, y, z]
# want the list whose ith element is the mean of a[0][i], a[1][i], ...,
# method 1: for loops
means1 = [0 for i in range(len(a[0]))]
n = len(a)
for i in range(len(a[0])):
for j in range(len(a)):
means1[i] = means1[i] + a[j][i]/n
[ ]: # method 3: vectorization
means3 = sum(a)/len(a)
print(means1, means2, means3)
[ ]:
2
3 Debugging
• A bug is an error in your code. How do we fix them?
[ ]: for i in range(2)
print(i)
[ ]: def f(x):
y = [x]
z = y.append(x + 1)
return z
f(1)
Adding print statements to your code can tell you values of variables, whether a function was
called, how far your program got before stopping, …
• print statement debugging: indicate position, var names
• Thonny debugging
• pythontutor frame diagrams
3
Should we store all the bn in a list? Could work, but it’s a bad idea. We only need one of them,
so it’s very inefficient.
b = ...
# loop invariant: at the end of the loop, b is the (k+1)st term of the␣
↪sequence
return b
If the loop invariant is true initially, and if the loop body preserves its truth, then at the end of
the loop it will still be true. So b will be b𝑛 .
[ ]: bs(100, [100])