0% found this document useful (0 votes)
47 views6 pages

Sol CH 1

Uploaded by

tranngocphung583
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views6 pages

Sol CH 1

Uploaded by

tranngocphung583
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

44 1 The first few steps

1.8.4 Deleting data no longer in use


Python has automatic garbage collection, meaning that there is no need
to delete variables (or objects) that are no longer in use. Python takes
care of this by itself. This is opposed to, e.g., Matlab, where explicit
deleting sometimes may be required.

1.8.5 Code lines that are too long


If a code line in a program gets too long, it may be continued on the next
line by inserting a back-slash at the end of the line before proceeding
on the next line. However, no blanks must occur after the back-slash! A
little demonstration could be the following,
my_sum = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13 +\
14 + 15 + 16 + 17 + 18 + 19 + 20

So, the back-slash works as a line continuation character here.

1.8.6 Where to find more information?


We have already recommended Langtangen’s book, A Primer on Scientific
Programming with Python (Springer, 2016), as the main reference for the
present book.
In addition, there is, of course, the official Python documenta-
tion website (http://docs.python.org/), which provides a Python
tutorial, the Python Library Reference, a Language Reference, and
more. Several other great books are also available, check out, e.g.,
http://wiki.python.org/moin/PythonBooks.
As you do know, search engines like Google are excellent for finding
information quickly, so also with Python related questions! Finally, you
will also find that the questions and answers at http://stackoverflow.
com often cover exactly what you seek. If not, you may ask your own
questions there.

1.9 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
1.9 Exercises 45

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

This error message basically tells us 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
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

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.
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: {}’.format(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 separate variables in the program. Run the
program and confirm that the correct results are printed.
Solution. The code reads:
import math as m

r = 2
C = 2*m.pi*r
A = m.pi*r**2

print(’Circumference: {:g}, Area: {:g}’.format(C, A))


1.9 Exercises 47

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 = L3 ,
computed for three different values of L.
a) In a program, use the linspace function to compute and print 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.
import numpy as np

L = np.linspace(1, 3, 3)
print(L)

b) Carry out, by hand, the computation V = L3 when 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) Modify the program in a), so that it prints out the result V of V =
L**3 when L is an array with three elements as computed by linspace.
Compare the resulting volumes with your hand calculations.
Solution. The code reads:
import numpy as np

L = np.linspace(1, 3, 3)
V = L**3
print(’Volumes: {}’.format(V))

Running the program gives the printout


Volumes: [ 1. 8. 27. ]

d) Make a plot of V versus L.


48 1 The first few steps

Solution. The code reads:


import matplotlib.pyplot as plt
plt.plot(L, V)
plt.xlabel(’Length of side’)
plt.ylabel(’Volume’)
plt.show()

The plot looks like

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.

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
print(’average: {}’.format(average))
1.9 Exercises 49

Running the program gives


average: 3.0

Filename: average_int.py.

Exercise 1.6: 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:


import math as m

x = m.pi
y = 2
z = x*y

print(’Multiplying {:g} and {:g} gives {:g}’.format(x, y, z))

Running the program prints the requested output.


Filename: formatted_print.py.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy