Errors#
At this point of the course, you have undoubtedly encountered many different errors in Python and (hopefully) fixed at the very least most of them. In this notebook, we will look at the most common types of errors you might run into, and some common fixes for these.
It is your job to fix these errors using the techniques you learned in PA1.7 on debugging. You will pass this notebook if you are able to run everything without throwing any errors. Before starting the notebook, please read through this chapter in the book om error types and this page for more information on debugging.
\(\text{Task 4.1:}\)
Fix the errors in the cells below.
Syntax Errors#
The code below has several syntax errors. See if you can fix them! For more details about syntax errors, please refer to the MUDE book.
# This function should take a list of numbers and check if each item is higher than 10 or not
# If it is higher than 10, it should print the value, otherwise it should print "not over 10"
# Corrected version:
def over_10(input):
for i in input:
if i > 10:
print(f"Value: {number}")
else:
print("not over 10")
Name and Scope Errors#
The code below has several name and scope errors.
# The code below is supposed to sum all even numbers in a list and print the last even number processed
# Corrected version:
total_sum = 0
def sum_even_numbers(numbers):
global total_sum
print("Starting sum with previous value:", total_sum)
last_even = None
for n in numbers:
if n % 2 == 0:
total_sum += n
last_even = n
print("Last even number processed:", last_even)
return total_sum, last_even
nums = [3, 6, 2, 7, 8, 5]
total, last_even = sum_even_numbers(nums)
print("The last even number in the list was:", last_even)
print("Total sum of even numbers:", total)
Starting sum with previous value: 0
Last even number processed: 8
The last even number in the list was: 8
Total sum of even numbers: 16
Type and Attribute Errors#
The code below has several Type and Attribute Errors. See if you can fix them.
# The code below is supposed to create a Person object and return it
# It should then print the name of the person, in this case 'John'
# Corrected version:
class Person:
def __init__(self, name):
self.name = name
def create_person():
return Person("John")
p = create_person()
print(p.name)
John
File and Import Errors#
The code below has two errors in them. See if you can fix them.
import os
from urllib.request import urlretrieve
def findfile(fname):
filepath = os.path.join('auxiliary_files', fname)
if not os.path.isfile(filepath):
os.makedirs('auxiliary_files', exist_ok=True)
print(f"Downloading {fname}...")
urlretrieve('https://github.com/TUDelft-MUDE/source-files/raw/main/file/'+fname, filepath)
findfile('numbers.csv')
Downloading numbers.csv...
# The code below is supposed to read a CSV file using pandas and print its contents
# Corrected version:
import pandas as pd
file = pd.read_csv('auxiliary_files/numbers.csv')
print(file)
Number Word
0 1 One
1 2 Two
2 3 Three
3 4 Four
4 5 Five
5 6 Six
6 7 Seven
7 8 Eight
8 9 Nine
9 10 Ten
10 11 Eleven
11 12 Twelve
12 13 Thirteen
13 14 Fourteen
14 15 Fifteen
15 16 Sixteen
16 17 Seventeen
17 18 Eighteen
18 19 Nineteen
19 20 Twenty
20 21 Twenty-One
21 22 Twenty-Two
22 23 Twenty-Three
23 24 Twenty-Four
Index Errors#
See if you can identify and fix the index errors in the code below.
# This code is supposed to create a 5x5 matrix with 5s on the diagonal and 1s just above the diagonal
# Corrected version:
import numpy as np
A = np.zeros((5, 5))
np.fill_diagonal(A, 5)
A[range(3), range(1, 4)] = 1
A mixed bag#
As you probably know by now, errors also rarely exist in isolation. Usually, you get a bundle of them that you need to fix one after another. Below is a snippet of code that have several errors of different types in them. See if you can fix the code!
import numpy as n # imported as n
# Corrected version:
a = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
b = np.linspace(0, 9, 10)
for i in range(len(a)):
a[i] = a[i] + (a[i-1] if i > 0 else 0)
c = a + b
print(c)
[ 0. 2. 5. 9. 14. 20. 27. 35. 44. 54.]
Logical Errors#
Logical errors are usually the most difficult errors to deal with as the code will still run without any errors and you do not get any hints on what is wrong.
This PA includes a .py files with code that contains logical errors: max_square_even.py. Try using the Python debugger for these, as then you can see how the variables change step-by-step!
\(\text{Task 4.2:}\)
Fix the errors in the .py file.
By Jialei Ding and Robert Lanzafame, Delft University of Technology. CC BY 4.0, more info on the Credits page of Workbook.