Sol CH 1
Sol CH 1
1.9 Exercises
one. For each error introduced, save and run the program, and comment
how well Python’s response corresponds to the actual error. When you
are finished with one error, re-set the program to correct behavior (and
check that it works!) before moving on to the next error.
a) Insert the word hello on the empty line above the assignment to v0.
Solution. An error message is printed, which at the end states that
NameError: name ’hello’ is not defined
Python repeats the particular code line where the problem is. Then, it
tells us that there is a syntax error in this line. It is up to the programmer
to find the syntax error in the line.
c) Remove the = sign in the assignment to v0.
Solution. An error message is printed, which at the end states that
v0 5 #initial velocity
SyntaxError: invalid syntax
Python repeats the particular code line where the problem is. Then, it
tells us that there is a syntax error in this line. It is up to the programmer
to find the syntax error in the line.
d) Change the reserved word print into pint.
Solution. An error message is printed, which at the end states that
pint y
NameError: name ’pint’ is not defined
This error message basically tells us what is wrong. Look out for spelling
errors, they are often to blame.
e) Change the calculation of y to y = v0*t.
Solution. We get no error message this time, even if the calculation of
y is wrong! This is because, to Python, the "new" way of calculating y is
perfectly legal, and Python can not know what we wanted to compute.
This is therefore another kind of error that sometimes may be hard to
find, since we get no error message. To find such errors, answers have to
be analyzed quantitatively in some way.
46 1 The first few steps
Python repeats the particular code line where the problem is. Then, it
explicitly tells us the problem, namely that x is not defined.
Filename: testing_ball.py.
Filename: cube_volume.py.
r = 2
C = 2*m.pi*r
A = m.pi*r**2
Filename: circumference_and_area.py.
L = np.linspace(1, 3, 3)
print(L)
L = np.linspace(1, 3, 3)
V = L**3
print(’Volumes: {}’.format(V))
30
25
20
Volume
15
10
0
1.0 1.5 2.0 2.5 3.0
Length of side
Remark. Observe that straight lines are drawn between the three points.
To make a smoother cubic curve V = L3 , we would need to compute
more L and V values on the curve.
Filename: volume3cubes.py.
Filename: average_int.py.
x = m.pi
y = 2
z = x*y