This chapter is taken from the book A Primer on Scientific Programming with Python by H. P. Langtangen, 5th edition, Springer, 2016.
A program is a collection of statements stored in a text file. Statements can also be executed interactively in a Python shell. Any error in any statement may lead to termination of the execution or wrong results. The computer does exactly what the programmer tells the computer to do!
some_variable = obj
defines a variable with the name some_variable
which refers to an
object obj
. Here obj
may also represent an expression, say a
formula, whose value is a Python object. For example, 1+2.5
involves
the addition of an int
object and a float
object, resulting in a
float
object. Names of variables can contain upper and lower case
English letters, underscores, and the digits from 0 to 9, but the name
cannot start with a digit. Nor can a variable name be a reserved word
in Python.
If there exists a precise mathematical description of the problem to be solved in a program, one should choose variable names that are in accordance with the mathematical description. Quantities that do not have a defined mathematical symbol, should be referred to by descriptive variables names, i.e., names that explain the variable's role in the program. Well-chosen variable names are essential for making a program easy to read, easy to debug, and easy to extend. Well-chosen variable names also reduce the need for comments.
Everything after #
on a line is ignored by Python and used to
insert free running text, known as comments. The purpose of comments
is to explain, in a human language, the ideas of (several) forthcoming
statements so that the program becomes easier to understand for
humans. Some variables whose names are not completely self-explanatory
also need a comment.
There are many different types of objects in Python. In this document we have worked with the following types.
Integers (whole numbers, object type int
):
x10 = 3
XYZ = 2
Floats (decimal numbers, object type float
):
max_temperature = 3.0
MinTemp = 1/6.0
Strings (pieces of text, object type str
):
a = 'This is a piece of text\nover two lines.'
b = "Strings are enclosed in single or double quotes."
c = """Triple-quoted strings can
span
several lines.
"""
Complex numbers (object type complex
):
a = 2.5 + 3j
real = 6; imag = 3.1
b = complex(real, imag)
Operators in arithmetic expressions follow the rules from mathematics: power is evaluated before multiplication and division, while the latter two are evaluated before addition and subtraction. These rules are overridden by parentheses. We suggest using parentheses to group and clarify mathematical expressions, also when not strictly needed.
-t**2*g/2
-(t**2)*(g/2) # equivalent
-t**(2*g)/2 # a different formula!
a = 5.0; b = 5.0; c = 5.0
a/b + c + a*c # yields 31.0
a/(b + c) + a*c # yields 25.5
a/(b + c + a)*c # yields 1.6666666666666665
Particular attention must be paid to coding fractions, since the
division operator /
often needs extra parentheses that are not
necessary in the mathematical notation for fractions (compare
\( \frac{a}{b+c} \) with a/(b+c)
and a/b+c
).
The math
module contains common mathematical functions for real
numbers. Modules must be imported before they can be used. The three
types of alternative module import go as follows:
# Import of module - functions requires prefix
import math
a = math.sin(math.pi*1.5)
# Import of individual functions - no prefix in function calls
from math import sin, pi
a = sin(pi*1.5)
# Import everything from a module - no prefix in function calls
from math import *
a = sin(pi*1.5)
To print the result of calculations in a Python program to a terminal
window, we apply the print
command, i.e., the word print
followed
by a string enclosed in quotes, or just a variable:
print "A string enclosed in double quotes"
print a
Several objects can be printed in one statement if the objects are separated by commas. A space will then appear between the output of each object:
>>> a = 5.0; b = -5.0; c = 1.9856; d = 33
>>> print 'a is', a, 'b is', b, 'c and d are', c, d
a is 5.0 b is -5.0 c and d are 1.9856 33
The printf syntax enables full control of the formatting of real numbers and integers:
>>> print 'a=%g, b=%12.4E, c=%.2f, d=%5d' % (a, b, c, d)
a=5, b= -5.0000E+00, c=1.99, d= 33
Here, a
, b
, and c
are of type float
and formatted as compactly
as possible (%g
for a
), in scientific notation with 4 decimals in
a field of width 12 (%12.4E
for b
), and in decimal notation with
two decimals in as compact field as possible (%.2f
for c
). The
variable d
is an integer (int
) written in a field of width 5
characters (%5d
).
A common error in mathematical computations is to divide two integers, because this results in integer division (in Python 2).
9/5
is
written as 9.0/5
, 9./5
, 9/5.
, or 9/5.0
.a/b
, ensure that a
or b
is a
float
object, and if not (or uncertain), do an explicit conversion
as in float(a)/b
to guarantee float division.a//b
.a/b
as float division also when a
and b
are integers.
Values of complex numbers are written as (X+Yj)
, where X
is the
value of the real part and Y
is the value of the imaginary part. One
example is (4-0.2j)
. If the real and imaginary parts are available
as variables r
and i
, a complex number can be created by
complex(r, i)
.
The cmath
module must be used instead of math
if the argument is a
complex variable. The numpy
package offers similar mathematical
functions, but with a unified treatment of real and complex variables.
Some Python and computer science terms briefly covered in this document are
print 'Hello!'
first makes a string object of the text in quotes and then the contents of this string object, without a name, is printed)What is the trajectory of a ball that is thrown or kicked with an initial velocity \( v_0 \) making an angle \( \theta \) with the horizontal? This problem can be solved by basic high school physics as you are encouraged to do in Exercise 13: Derive the trajectory of a ball. The ball will follow a trajectory \( y=f(x) \) through the air where $$ \begin{equation} f(x) = x\tan\theta - {1\over 2v_0^2}{gx^2\over\cos^2\theta} + y_0\tp \tag{6} \end{equation} $$ In this expression, \( x \) is a horizontal coordinate, \( g \) is the acceleration of gravity, \( v_0 \) is the size of the initial velocity that makes an angle \( \theta \) with the \( x \) axis, and \( (0,y_0) \) is the initial position of the ball. Our programming goal is to make a program for evaluating (6). The program should write out the value of all the involved variables and what their units are.
We remark that the formula (6) neglects air resistance. Exercise 11: Compute the air resistance on a football explores how important air resistance is. For a soft kick (\( v_0=30 \) km/h) of a football, the gravity force is much larger than the air resistance, but for a hard kick, air resistance may be as important as gravity.
We use the SI system and assume that \( v_0 \) is given in km/h; \( g =
9.81\hbox {m/s}^2 \); \( x \), \( y \), and \( y_0 \) are measured in meters; and
\( \theta \) in degrees. The program has naturally four parts:
initialization of input data, import of functions and \( \pi \) from
math
, conversion of \( v_0 \) and \( \theta \) to m/s and radians,
respectively, and evaluation of the right-hand side expression in
(6). We choose to write out all
numerical values with one decimal. The complete program is found in
the file trajectory.py:
g = 9.81 # m/s**2
v0 = 15 # km/h
theta = 60 # degrees
x = 0.5 # m
y0 = 1 # m
print """\
v0 = %.1f km/h
theta = %d degrees
y0 = %.1f m
x = %.1f m\
""" % (v0, theta, y0, x)
from math import pi, tan, cos
# Convert v0 to m/s and theta to radians
v0 = v0/3.6
theta = theta*pi/180
y = x*tan(theta) - 1/(2*v0**2)*g*x**2/((cos(theta))**2) + y0
print 'y = %.1f m' % y
The backslash in the triple-quoted multi-line string makes the string
continue on the next line without a newline. This means that removing
the backslash results in a blank line above the v0
line and a blank
line between the x
and y
lines in the output on the screen.
Another point to mention is the expression 1/(2*v0**2)
, which might
seem as a candidate for unintended integer division. However, the
conversion of v0
to m/s involves a division by 3.6, which results in
v0
being float
, and therefore 2*v0**2
being float
. The rest
of the program should be self-explanatory at this stage in the
document.
We can execute the program in IPython or an ordinary terminal window and watch the output:
v0 = 15.0 km/h
theta = 60 degrees
y0 = 1.0 m
x = 0.5 m
y = 1.6 m
This version of the document applies different design elements for different types of "computer text". Complete programs and parts of programs (snippets) are typeset with a light blue background. A snippet looks like this:
a = sqrt(4*p + c)
print 'a =', a
A complete program has an additional, slightly darker frame:
C = 21
F = (9.0/5)*C + 32
print F
As a reader of this document, you may wonder if a code shown is a complete program you can try out or if it is just a part of a program (a snippet) so that you need to add surrounding statements (e.g., import statements) to try the code out yourself. The appearance of horizontal lines or not will then quickly tell you what type of code you see.
An interactive Python session is typeset as
>>> from math import *
>>> p = 1; c = -1.5
>>> a = sqrt(4*p + c)
Running a program, say ball_yc.py
, in the terminal window,
followed by some possible output
is typeset as
ball_yc.py
At t=0.0417064 s and 0.977662 s, the height is 0.2 m.
Recall from the section IPython that we just write the
program name. A real execution demands prefixing the program name by
python
in a terminal window, or by run
if you run the
program from an interactive IPython session. We refer to
the
document Different ways of running Python programs [2] for more
complete information on running Python programs in different ways.
Sometimes just the output from a program is shown, and this output appears as plain computer text:
h = 0.2 order=0, error=0.221403 order=1, error=0.0214028 order=2, error=0.00140276 order=3, error=6.94248e-05 order=4, error=2.75816e-06
Files containing data are shown in a similar way in this document:
date Oslo London Berlin Paris Rome Helsinki 01.05 18 21.2 20.2 13.7 15.8 15 01.06 21 13.2 14.9 18 24 20 01.07 13 14 16 25 26.2 14.5
This book presents Python code that is (mostly) in accordance with the official Style Guide for Python Code, known in the Python community as PEP8. Some exceptions to the rules are made to make code snippets shorter: multiple imports on one line and less blank lines.