$$ \newcommand{\Oof}[1]{\mathcal{O}(#1)} \newcommand{\F}{\boldsymbol{F}} \newcommand{\J}{\boldsymbol{J}} \newcommand{\x}{\boldsymbol{x}} \renewcommand{\c}{\boldsymbol{c}} $$

 

 

 

Exercises

Exercise 1.1: Error messages

Save a copy of the program ball.py and confirm that the copy runs as the original. You are now supposed to introduce errors in the code, one by 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

The error message tells us explicitly what is wrong.

b) Remove the # sign in front of the comment initial velocity.

Solution.

An error message is printed, which 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.

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
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.

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.

f) Change the line print y to print x.

Solution.

An error message is printed, which at the end states that

    print x
NameError: name 'x' is not defined

Python repeats the particular code line where the problem is. Then, it explicitly tells us the problem, namely that x is not defined.

g) Replace the statement

y = v0*t - 0.5*g*t**2

by

y = v0*t - (1/2)*g*t**2

Solution.

We get no error message, but the wrong answer 3 (instead of 1.2342). The problem is that 1/2 is an integer divison that rounds to zero, so the computation now becomes equivalent to y = v0*t, which is wrong.

Filename: testing_ball.py.

Exercise 1.2: Volume of a cube

Write a program that computes the volume \( V \) of a cube with sides of length \( L = 4 \) cm and prints the result to the screen. Both \( V \) and \( L \) should be defined as separate variables in the program. Run the program and confirm that the correct result is printed.

Hint.

See ball.py in the text.

Solution.

The code reads:

L = 4       # i.e., in cm
V = L**3
print "The volume is: ", V

Running the program gives the output

The volume is: 64

Filename: cube_volume.py.

Exercise 1.3: Area and circumference of a circle

Write a program that computes both the circumference \( C \) and the area \( A \) of a circle with radius \( r = 2 \) cm. Let the results be printed to the screen on a single line with an appropriate text. The variables \( C \), \( A \) and \( r \) should all be defined as a separate variables in the program. Run the program and confirm that the correct results are printed.

Solution.

The code reads:

from math import *

r = 2
C = 2*pi*r
A = pi*r**2

print "Circumference: %g, Area: %g" % (C, A)

Running the program gives the output

Circumference: 12.5664, Area: 12.5664

Filename: circumference_and_area.py.

Exercise 1.4: Volumes of three cubes

We are interested in the volume \( V \) of a cube with length \( L \): \( V=L^3 \), computed for three different values of \( L \).

a) Use the linspace function to compute three values of \( L \), equally spaced on the interval \( [1,3] \).

Solution.

We must remember to import the function linspace before we can use it.

In [1]: from numpy import linspace
In [2]: linspace(1, 3, 3)
Out [2]: array([1., 2., 3.])

b) Carry out by hand the computation \( V=L^3 \) if \( L \) is an array with three elements. That is, compute \( V \) for each value of \( L \).

Solution.

You should get 1, 8 and 27, which afterwards should compare favorably to output from the code.

c) In a program, write out the result V of V = L**3 when L is an array with three elements as computed by linspace in a). Compare the resulting volumes with your hand calculations.

Solution.

The code reads:

from numpy import *

L = linspace(1, 3, 3)
V = L**3
print "Volumes:", V

Running the program gives the printout

Volumes: [ 1. 8. 27. ]

d) Make a plot of V versus L.

Solution.

The code reads:

from matplotlib.pyplot import *
plot(L, V)
xlabel('Length of side')
ylabel('Volume')

The plot looks like

Remark. Observe that straight lines are drawn between the three points. To make a smoother cubic curve \( V=L^3 \), we would need to compute more \( L \) and \( V \) values on the curve.

Filename: volume3cubes.py.

Exercise 1.5: Average of integers

Write a program that stores the sum \( 1+2+3+4+5 \) in one variable and then creates another variable with the average of these five numbers. Print the average to the screen and check that the result is correct.

Solution.

The code reads:

sum = 1 + 2 + 3 + 4 + 5
average = sum/5.0
print "average: ", average

Running the program gives

average: 3.0

Filename: average_int.py.

Exercise 1.6: Interactive computing of volume and area

a) Compute the volume in Exercise 1.2: Volume of a cube by using Python interactively, i.e., do the computations at the command prompt (in a Python shell as we also say). Compare with what you got previously from the written program.

Solution.

In [1]: L = 4
In [2]: V = L**3
In [3]: print "The volume is: ", V
The volume is: 64

b) Do the same also for Exercise 1.3: Area and circumference of a circle.

Solution.

from math import *
In [1]: r = 2
In [2]: C = 2*pi*r
In [3]: A = pi*r**2
In [4]: print "Circumference: %g, Area: %g " % (C,A)
Circumference: 12.5664, Area: 12.5664

Exercise 1.7: Peculiar results from division

Consider the following interactive Python session:

In [1]: x=2; y=4

In [2]: x/y
Out[2]: 0

What is the problem and how can you fix it?

Solution.

Because of integer division Python will round this to zero (since the numerator is smaller than the denominator). The problem may be fixed by using the function float either in the numerator or in the denominator (or in both places). If we use float in the numerator, the code line with the division reads:

In [2]: float(x)/y

The answer then correctly becomes \( 0.5 \).

Exercise 1.8: Update variable at command prompt

Invoke Python interactively and perform the following steps.

  1. Initialize a variable x to 2.
  2. Add 3 to x. Print out the result.
  3. Print out the result of x + 1*2 and (x+1)*2. (Observe how parentheses make a difference).
  4. What variable type is x?

Solution.

In [1]: x = 2
In [2]: x += 3
In [3]: print x + 1*2
7
In [4]: print (x + 1)*2
12
In [5]: type(x)
Out [5]: int

Exercise 1.9: Formatted print to screen

Write a program that defines two variables as x = pi and y = 2. Then let the program compute the product z of these two variables and print the result to the screen as

Multiplying 3.14159 and 2 gives 6.283

Solution.

The code reads:

from math import pi

x = pi
y = 2
z = x*y

print "Multiplying %g and %g gives %g" % (x, y, z)

Running the program prints the requested output.

Filename: formatted_print.py.

Exercise 1.10: Python documentation and random numbers

Write a program that prints four random to the screen. The numbers should be drawn from a uniform distribution over the interval \( [0,10) \) (0 inclusive, 10 exclusive). Find the information needed for the task, see for example http://docs.python.org.

Hint.

Python has a module random that contains a function by the name uniform.

Solution.

The code reads:

import random
print random.uniform(0, 10)
print random.uniform(0, 10)
print random.uniform(0, 10)
print random.uniform(0, 10)

Running the program gives for example (note that numbers change when you run the program again)

7.04892469523
4.64465984386
8.46022195385
0.458184395321

Filename: drawing_random_numbers.py.