Sol CH 4
Sol CH 4
Sol CH 4
The constructions met in this chapter, and the previous chapter, are
characterized by a grouping of statements that generally span several
lines (although it is possible to write simpler cases on a single line,
when statements are separated with a semi-colon). Such construc-
tions are often referred to as compound statements, having headers
(ending with a colon) and bodies (with indented statements)a .
Interactive handling of compound statements is straight forward.
For example, a for loop may be written (and executed) like
In [1]: for i in [1, 2, 3]: # write header, press enter
...: print(i) # indent comes automatically
...: # press only enter, i.e., finished
1
2
3
When the header has been typed in and we press enter, we are
automatically given the indent on the next line. We can then proceed
directly by writing print(i) and press enter again. We then want
to finish our loop, which is understood when we simply press enter,
writing nothing else.
a
https://docs.python.org/3/reference/compound_stmts.html
4.3 Exercises
^
SyntaxError: invalid syntax
Python repeats the line where it found a problem and then tells us that
the line has a syntax error. It is up to the programmer to find the error,
although a little "hat" is used to show were in the line Python thinks the
problem is. In this case, that "hat" is placed underneath where the colon
should have been placed.
b) Remove the indent in front of the statement g = 9.81 inside the
function y, i.e., shift the text four spaces to the left.
Solution. Running the program gives an indentation error:
g = 9.81
^
IndentationError: expected an indented block
Python repeats the line where it found the syntax problem and states
that (somewhere in this line) there is a syntax error.
130 4 Functions and the writing of code
e) Change the first line of the function definition from def y(v0, t):
to def y(v0):, i.e., remove the parameter t (and the comma).
Solution. Running the program gives a type error:
print(y(v0, time))
Python repeats the line where it found a syntax problem and tells us
that the function y is used in the wrong way, since two arguments were
used when calling it. To Python, this is the logical way of responding,
since Python chooses to believe that our definition of the function was
correct. This definition (which actually is what is wrong!) states that
the function takes only one parameter. By comparing with the function
definition, it is up to the programmer to understand whether such an
error is in the function definition (as here) or in the function call.
f) Change the first occurrence of the command print(y(v0, time))
to print(y(v0)).
Solution. Running the program gives a type error:
print(y(v0))
Python repeats the line where it found a syntax problem and tells us that
the function y is used in the wrong way, since one positional argument
is missing in the call. Again, Python discovered a mismatch between
function definition and use of the function. Now, the definition specifies
two positional parameters, whereas the call uses only one.
Filename: errors_colon_indent_etc.py.
print(f(x))
elif x == 5:
# case 2
print(2*f(x))
elif x > 5 and x < 8:
# case 3
print(f(x+4) + g(x*2) - g(2))
else:
# case 4
y = x + 2
print(g(y))
Solution. The following numbers are printed: 1, 50, 120, 22, in this
order.
b) Type in the code and run the program to confirm that your predictions
are correct.
Filename: read_code_1.py.
x = 0
for i in range(0, 4, 1):
x += i
print(x)
def circumference(r):
return 2*m.pi*r
def area(r):
return m.pi*r**2
Filename: functions_circumference_area.py.
x = np.array([1, 3, 5])
y = np.array([2, 4, 6])
z = np.array([2, 4])
Filename: add_vectors.py.
Filename: function_area_rectangle.py.
Filename: average_1_to_N.py.
def f(x):
return x
def g(x):
return x**2
for i in range(N):
if abs(f(x_values[i]) - g(x_values[i])) < epsilon:
print(x_values[i])
Running the program with 400 check-points (i.e. N = 400) and an error
tolerance of 0.01 (i.e. epsilon = 0.01) gives the following dialog:
Give the number of check-points N: 400
y = np.zeros(5)
y[0] = 4.4; y[1] = 2.0; y[2] = 11.0;
y[3] = 21.5; y[4] = 7.5
find_y(y, dt)
Filename: linear_interpolation.py.
f (xi ) − f (c)
= a, i = 1, 2, . . . , 100 ,
xi − c
where a is the slope of the line and c defines a fixed point (c, f (c)) on
the line. Let c = 2 here.
Solution. The code may be written as follows
"""
For a straight line f(x) = ax + b, and the fixed point (2,f(2)) on
the line, the script tests whether (f(x_i) - f(2)) / (x_i - 2) = a
for randomly chosen x_i, i = 1,...,100.
"""
def f(x):
return a*x + b
a = 4.0; b = 1.0
c = 2; f_c = f(c) # Fixed point on the line
epsilon = 1e-6
i = 0
for i in range(100):
x = 10*random() # random() returns number between 0 and 1
numerator = f(x) - f_c
denominator = x - c
if denominator > epsilon: # To avoid zero division
fraction = numerator/denominator
# The following printout should be very close to zero in
# each case if the points are on the line
print(’For x = {:g} : {:g}’.format(x,abs(fraction - a)))
def f(t,a,b):
return a*t + b
def interactive_line_fit():
one_more = True
while one_more:
a = float(input(’Give a: ’))
b = float(input(’Give b: ’))
print(’The error is: {:g}’.format(find_error(a, b)))
y = f(time, a, b)
plt.plot(time, y, time, data, ’*’)
plt.xlabel(’Time (s)’)
plt.ylabel(’y (stars) and straight line f(t)’)
4.3 Exercises 141
Fig. 4.2 Straight line fitted to data with second choice of line parameters (a and b).
def test_sinesum():
t = zeros(2); t[0] = -pi/2; t[1] = pi/4
b = zeros(2); b[0] = 4.0; b[1] = -3
print(sinesum(t, b))
E = 0
for i in range(len(time)):
E += sqrt((y[i] - S[i])**2)
return E
def f(t):
return (1/pi)*t
Fig. 4.3 Straight line fitted to data with first choice of line parameters (a and b).
Filename: fit_sines.py.
Remarks.
1. The function SN (x) is a special case of what is called a Fourier series.
At the beginning of the 19th century, Joseph Fourier (1768-1830)
showed that any function can be approximated analytically by a sum
of cosines and sines. The approximation improves as the number of
terms (N ) is increased. Fourier series are very important throughout
science and engineering today.
a. Finding the coefficients bn is solved much more accurately in
Exercise 6.12, by a procedure that also requires much less human
and computer work!
b. In real applications, f (t) is not known as a continuous function,
but function values of f (t) are provided. For example, in digital
sound applications, music in a CD-quality WAV file is a signal
with 44100 samples of the corresponding analog signal f (t) per
second.