This chapter is taken from the book A Primer on Scientific Programming with Python by H. P. Langtangen, 5th edition, Springer, 2016.
There is only one way to learn programming: you have to program yourself. This means that you have to do a lot of exercises! Reading this book is necessary to learn about the Python syntax and studying the examples in depth is necessary to grasp how to think about programming and solving problems. But the main effort in the learning process is your work with exercises or your own programming projects.
Solving an exercise is a three-stage procedure. First, you have to study the text in the exercise carefully to understand what the problem is about. Programming exercises, especially in this book, are about a problem setting that has to be thoroughly understood before it makes sense to understand the specific questions in the exercise. The second phase is to write the program. The more efforts you put into the first phase, the easier it will be to find the right statements and write the code. The third and final stage is to test the program and remove errors (known as debugging and verification from the section Computer science glossary). This is by far the greatest challenge for beginners. Very often, especially for newcomers to programming, it boils down to writing out the result of every statement and checking these results carefully by playing computer with pen and paper.
Beginners often underestimate the amount of work required in the first and third stage and instead try to do the second stage (i.e., write the program) as quickly as possible. The more work you put into the first stage, the easier it will be to find an example in this book or elsewhere that is similar to the exercise and that can help you get started. And the more work you put into stage three up front, with constructing a test case, the better your understanding of the statements will be and the fewer errors you will commit. Experience will prove that all these assertions are right!
Most exercises are associated with a filename, e.g., myexer
.
If the answer to the exercise is a Python program, you should store
the program in a file myexer.py
. If the answer can be an explanation,
you may store it in a plain text file, myexer.txt
, or write the text in a
word processor and produce a PDF file (myexer.pdf
).
When you hand in exercises to teaching assistants, it is often a
requirement that a trial run of the program is inserted at the end
of the code. This means that you run some case with known result,
direct the output to a file result
,
Terminal> python myprogram.py > result
and copy the contents of result
to a triple-quoted string with
appropriate comments after the statements of the program. Here is an
example of a program with its trial run inserted:
F = 69.8 # Fahrenheit degrees
C = (5.0/9)*(F - 32) # Corresponding Celsius degrees
print C
'''
Trial run (correct result is 21):
python f2c.py
21.0
'''
The trial run demonstrates that the program runs and produces correct results in a test case.
The first exercise concerns some very basic mathematics and
programming: assign the result of 1+1 to a variable and print the
value of that variable.
Filename: 1plus1
.
Almost all books about programming languages start with a very simple
program that prints the text Hello, World!
to the screen.
Make such a program in Python.
Filename: hello_world
.
Can a newborn baby in Norway expect to live for one billion (\( 10^9 \))
seconds? Write a Python program for doing arithmetics to answer the
question.
Filename: seconds2years
.
Make a program where you set a length given in meters and then compute
and write out the corresponding length measured in inches, in feet, in
yards, and in miles. Use that one inch is 2.54 cm, one foot is 12
inches, one yard is 3 feet, and one British mile is 1760 yards. For
verification, a length of 640 meters corresponds to 25196.85 inches,
2099.74 feet, 699.91 yards, or 0.3977 miles.
Filename: length_conversion
.
The density of a substance is defined as \( \varrho = m/V \), where \( m \) is
the mass of a volume \( V \). Compute and print out the mass of one liter
of each of the following substances whose densities in \( \hbox{g/cm}^3 \)
are found in the file src/files/densities.dat: iron, air, gasoline, ice, the human
body, silver, and platinum.
Filename: 1liter
.
Let \( p \) be a bank's interest rate in percent per year. An initial amount
\( A \) has then grown to
$$
\begin{equation*} A\left(1 + {p\over 100}\right)^n\end{equation*}
$$
after \( n \) years. Make a program for computing how much money 1000 euros
have grown to after three years with 5 percent interest rate.
Filename: interest_rate
.
Suppose somebody has written a simple one-line program for computing \( \sin (1) \):
x=1; print 'sin(%g)=%g' % (x, sin(x))
Create this program and try to run it. What is the problem?
Filename: find_errors_sin1
.
Type the following program in your editor and execute it. If your program does not work, check that you have copied the code correctly.
from math import pi
h = 5.0 # height
b = 2.0 # base
r = 1.5 # radius
area_parallelogram = h*b
print 'The area of the parallelogram is %.3f' % area_parallelogram
area_square = b**2
print 'The area of the square is %g' % area_square
area_circle = pi*r**2
print 'The area of the circle is %.3f' % area_circle
volume_cone = 1.0/3*pi*r**2*h
print 'The volume of the cone is %.3f' % volume_cone
Filename: formulas_shapes
.
Type these short programs in your editor and execute them. When they do not work, identify and correct the erroneous statements.
a) Does \( \sin^2(x) + \cos^2(x) = 1 \)?
from math import sin, cos
x = pi/4
1_val = math.sin^2(x) + math.cos^2(x)
print 1_VAL
b) Compute \( s \) in meters when \( s=v_0t + \frac{1}{2}at^2 \), with \( v_0=3 \) m/s, \( t=1 \) s, \( a=2\ \hbox{m/s}^2 \).
v0 = 3 m/s
t = 1 s
a = 2 m/s**2
s = v0.t + 0,5.a.t**2
print s
c) Verify these equations: $$ \begin{equation*} (a + b)^2 = a^2 + 2ab + b^2 \end{equation*} $$ $$ \begin{equation*} (a - b)^2 = a^2 - 2ab + b^2 \end{equation*} $$
a = 3,3 b = 5,3
a2 = a**2
b2 = b**2
eq1_sum = a2 + 2ab + b2
eq2_sum = a2 - 2ab + b2
eq1_pow = (a + b)**2
eq2_pow = (a - b)**2
print 'First equation: %g = %g', % (eq1_sum, eq1_pow)
print 'Second equation: %h = %h', % (eq2_pow, eq2_pow)
Filename: find_errors_programs
.
The bell-shaped Gaussian function,
$$
\begin{equation}
f(x) =
{1\over\sqrt{2\pi }\, s}
\exp{\left[-\frac{1}{2}\left({x-m\over s}\right)^2\right]},
\tag{7}
\end{equation}
$$
is one of the most widely used functions in science and technology.
The parameters \( m \) and \( s>0 \) are prescribed real numbers. Make a
program for evaluating this function when \( m=0 \), \( s=2 \), and
\( x=1 \). Verify the program's result by comparing with hand calculations
on a calculator.
Filename: gaussian1
.
The function (7) is named after Carl Friedrich Gauss, 1777-1855, who was a German mathematician and scientist, now considered as one of the greatest scientists of all time. He contributed to many fields, including number theory, statistics, mathematical analysis, differential geometry, geodesy, electrostatics, astronomy, and optics. Gauss introduced the function (7) when he analyzed probabilities related to astronomical data.
The drag force, due to air resistance, on an object can be expressed as $$ \begin{equation} F_d = \frac{1}{2} C_D \varrho AV^2, \tag{8} \end{equation} $$ where \( \varrho \) is the density of the air, \( V \) is the velocity of the object, \( A \) is the cross-sectional area (normal to the velocity direction), and \( C_D \) is the drag coefficient, which depends heavily on the shape of the object and the roughness of the surface.
The gravity force on an object with mass \( m \) is \( F_g = mg \), where \( g=9.81 \hbox{m}\,\hbox{s}^{-2} \).
We can use the formulas for \( F_d \) and \( F_g \) to study the importance of air resistance versus gravity when kicking a football. The density of air is \( \varrho = 1.2\ \hbox{kg }\,{\hbox{m}}^{-3} \). We have \( A=\pi a^2 \) for any ball with radius \( a \). For a football, \( a=11 \) cm and the mass is 0.43 kg. The drag coefficient \( C_D \) varies with the velocity and can be taken as 0.4.
Make a program that computes the drag force and the gravity force on a
football. Write out the forces with one decimal in units of Newton
(\( \hbox{N} = \hbox{kg}\,\hbox{m}/\hbox{s}^{2} \)). Also print the ratio
of the drag force and the gravity force. Define \( C_D \), \( \varrho \),
\( A \), \( V \), \( m \), \( g \), \( F_d \), and \( F_g \) as variables, and put a comment
with the corresponding unit. Use the program to calculate the forces
on the ball for a hard kick, \( V=120 \hbox{ km}/\hbox{h} \) and for a
soft kick, \( V=30 \hbox{ km}/\hbox{h} \) (it is easy to mix inconsistent
units, so make sure you compute with \( V \) expressed in m/s).
Filename: kick
.
As an egg cooks, the proteins first denature and then coagulate. When the temperature exceeds a critical point, reactions begin and proceed faster as the temperature increases. In the egg white, the proteins start to coagulate for temperatures above 63 C, while in the yolk the proteins start to coagulate for temperatures above 70 C. For a soft boiled egg, the white needs to have been heated long enough to coagulate at a temperature above 63 C, but the yolk should not be heated above 70 C. For a hard boiled egg, the center of the yolk should be allowed to reach 70 C.
The following formula expresses the time \( t \) it takes (in seconds) for
the center of the yolk to reach the temperature \( T_y \) (in Celsius
degrees):
$$
\begin{equation}
t = \frac{M^{2/3}c\rho^{1/3}}{K\pi^2(4\pi/3)^{2/3}}
\ln\left\lbrack 0.76\frac{T_o - T_w}{T_y-T_w}\right\rbrack\tp
\tag{9}
\end{equation}
$$
Here, \( M \), \( \rho \), \( c \), and \( K \) are properties of the egg: \( M \) is the
mass, \( \rho \) is the density, \( c \) is the specific heat capacity, and
\( K \) is thermal conductivity. Relevant values are \( M= 47 \) g for a
small egg and \( M=67 \) g for a large egg, \( \rho = 1.038\hbox{
g}\,\hbox{cm}^{-3} \), \( c=3.7\hbox{ J}\,\hbox{g}^{-1}\,\hbox{K}^{-1} \),
and \( K=5.4\cdot 10^{-3}\hbox{ W}\,\hbox{cm}^{-1}\,\hbox{K}^{-1} \).
Furthermore, \( T_w \) is the temperature (in C degrees) of the boiling
water, and \( T_o \) is the original temperature (in C degrees) of the egg
before being put in the water. Implement the formula in a program,
set \( T_w=100 \) C and \( T_y=70 \) C, and compute \( t \) for a large egg taken
from the fridge (\( T_o=4 \) C) and from room temperature (\( T_o=20 \) C).
Filename: egg
.
The purpose of this exercise is to explain how Equation (6) for the trajectory of a ball arises from basic physics. There is no programming in this exercise, just physics and mathematics.
The motion of the ball is governed by Newton's second law: $$ \begin{align} F_x &= ma_x \tag{10}\\ F_y &= ma_y \tag{11} \end{align} $$ where \( F_x \) and \( F_y \) are the sum of forces in the \( x \) and \( y \) directions, respectively, \( a_x \) and \( a_y \) are the accelerations of the ball in the \( x \) and \( y \) directions, and \( m \) is the mass of the ball. Let \( (x(t),y(t)) \) be the position of the ball, i.e., the horizontal and vertical coordinate of the ball at time \( t \). There are well-known relations between acceleration, velocity, and position: the acceleration is the time derivative of the velocity, and the velocity is the time derivative of the position. Therefore we have that $$ \begin{align} a_x &= {d^2 x\over dt^2}, \tag{12}\\ a_y &= {d^2 y\over dt^2}\tp \tag{13} \end{align} $$ If we assume that gravity is the only important force on the ball, \( F_x=0 \) and \( F_y=-mg \).
Integrate the two components of Newton's second law twice. Use the
initial conditions on velocity and position,
$$
\begin{align}
{d\over dt}x(0)&= v_0\cos\theta,
\tag{14}\\
{d\over dt}y(0)&= v_0\sin\theta,
\tag{15}\\
x(0) &= 0,
\tag{16}\\
y(0) &= y_0,
\tag{17}
\end{align}
$$
to determine the four integration constants. Write up the final
expressions for \( x(t) \) and \( y(t) \). Show that if \( \theta =\pi/2 \), i.e.,
the motion is purely vertical, we get the formula
(1) for the \( y \) position. Also show that if we
eliminate \( t \), we end up with the relation
(6) between the \( x \) and \( y \) coordinates
of the ball. You may read more about this type of motion in a physics
book, e.g., [6].
Filename: trajectory
.
Some versions of our program for calculating the formula (3) are listed below. Find the versions that will not work correctly and explain why in each case.
C = 21; F = 9/5*C + 32; print F
C = 21.0; F = (9/5)*C + 32; print F
C = 21.0; F = 9*C/5 + 32; print F
C = 21.0; F = 9.*(C/5.0) + 32; print F
C = 21.0; F = 9.0*C/5.0 + 32; print F
C = 21; F = 9*C/5 + 32; print F
C = 21.0; F = (1/5)*9*C + 32; print F
C = 21; F = (1./5)*9*C + 32; print F
Filename: find_errors_division
.
Figure out why the following program does not work:
C = A + B
A = 3
B = 2
print C
Filename: find_errors_vars
.
Try the following statements in an interactive Python shell. Explain why some statements fail and correct the errors.
1a = 2
a1 = b
x = 2
y = X + 4 # is it 6?
from Math import tan
print tan(pi)
pi = "3.14159'
print tan(pi)
c = 4**3**2**3
_ = ((c-78564)/c + 32))
discount = 12%
AMOUNT = 120.-
amount = 120$
address = hpl@simula.no
and = duck
class = 'INF1100, gr 2"
continue_ = x > 0
rev = fox = True
Norwegian = ['a human language']
true = fox is rev in Norwegian
It is wise to test the values of the expressions on the right-hand side, and the validity of the variable names, separately before you put the left- and right-hand sides together in statements. The last two statements work, but explaining why goes beyond what is treated in this document.
Filename: find_errors_syntax
.
Given a quadratic equation, $$ \begin{equation*} ax^2 + bx + c = 0,\end{equation*} $$ the two roots are $$ \begin{equation} x_1 = {-b + \sqrt{b^2 -4ac}\over 2a},\quad x_2 = {-b - \sqrt{b^2 -4ac}\over 2a}\tp \tag{18} \end{equation} $$ What are the problems with the following program?
a = 2; b = 1; c = 2
from math import sqrt
q = b*b - 4*a*c
q_sr = sqrt(q)
x1 = (-b + q_sr)/2*a
x2 = (-b - q_sr)/2*a
print x1, x2
Correct the program so that it solves the given equation.
Filename: find_errors_roots
.
What is the problem in the following program?
from math import pi, tan
tan = tan(pi/4)
tan2 = tan(pi/3)
print tan, tan2
Filename: find_errors_tan
.