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

 

 

 

A Python program with variables

Our first example regards programming a mathematical model that predicts the position of a ball thrown up in the air. From Newton's 2nd law, and by assuming negligible air resistance, one can derive a mathematical model that predicts the vertical position \( y \) of the ball at time \( t \). From the model one gets the formula $$ y = v_0 t - 0.5gt^2 , $$ where \( v_0 \) is the initial upwards velocity and \( g \) is the acceleration of gravity, for which \( 9.81\hbox{ ms}^{-2} \) is a reasonable value (even if it depends on things like location on the earth). With this formula at hand, and when \( v_0 \) is known, you may plug in a value for time and get out the corresponding height.

The program

Let us next look at a Python program for evaluating this simple formula. Assume the program is contained as text in a file named ball.py. The text looks as follows (file ball.py):

# Program for computing the height of a ball in vertical motion

v0 = 5             # Initial velocity
g = 9.81           # Acceleration of gravity
t = 0.6            # Time

y = v0*t - 0.5*g*t**2        # Vertical position

print y

Computer programs and parts of programs are typeset with a blue background in this book. A slightly darker top and bottom bar, as above, indicates that the code is a complete program that can be run as it stands. Without the bars, the code is just a snippet and will (normally) need additional lines to run properly.

Dissection of the program

A computer program is plain text, as here in the file ball.py, which contains instructions to the computer. Humans can read the code and understand what the program is capable of doing, but the program itself does not trigger any actions on a computer before another program, the Python interpreter, reads the program text and translates this text into specific actions.

You must learn to play the role of a computer. Although Python is responsible for reading and understanding your program, it is of fundamental importance that you fully understand the program yourself. You have to know the implication of every instruction in the program and be able to figure out the consequences of the instructions. In other words, you must be able to play the role of a computer. The reason for this strong demand of knowledge is that errors unavoidably, and quite often, will be committed in the program text, and to track down these errors, you have to simulate what the computer does with the program. Next, we shall explain all the text in ball.py in full detail.

When you run your program in Python, it will interpret the text in your file line by line, from the top, reading each line from left to right. The first line it reads is

# Program for computing the height of a ball in vertical motion.

This line is what we call a comment. That is, the line is not meant for Python to read and execute, but rather for a human that reads the code and tries to understand what is going on. Therefore, one rule in Python says that whenever Python encounters the sign # it takes the rest of the line as a comment. Python then simply skips reading the rest of the line and jumps to the next line. In the code, you see several such comments and probably realize that they make it easier for you to understand (or guess) what is meant with the code. In simple cases, comments are probably not much needed, but will soon be justified as the level of complexity steps up.

The next line read by Python is

v0 = 5	# Initial velocity

In Python, a statement like v0 = 5 is known as an assignment statement (very different from a mathematical equation!). The result on the right-hand side, here the integer 5, becomes an object and the variable name on the left-hand side is a named reference for that object. Whenever we write v0, Python will replace it by an integer with value 5. Doing v1 = v0 creates a new name, v1, for the same integer object with value 5 and not a copy of an integer object with value 5. The next two lines

g = 9.81  # Acceleration of gravity
t = 0.6   # Time

are of the same kind, so having read them too, Python knows of three variables (v0, g, t) and their values. These variables are then used by Python when it reads the next line, the actual "formula",

y = v0*t - 0.5*g*t**2		# Vertical position

Again, according to its rules, Python interprets * as multiplication, - as minus and ** as exponent (let us also add here that, not surprisingly, + and / would have been understood as addition and division, if such signs had been present in the expression). Having read the line, Python performs the mathematics on the right-hand side, and then assigns the result (in this case the number \( 1.2342 \)) to the variable name y. Finally, Python reads

print y

This makes Python print the value of y out in that window on the screen where you started the program. When ball.py is run, the number \( 1.2342 \) appears on the screen.

In the code above, you see several blank lines too. These are simply skipped by Python and you may use as many as you want to make a nice and readable layout of the code.

Why not just use a pocket calculator?

Certainly, finding the answer as done by the program above could easily have been done with a pocket calculator. No objections to that and no programming would have been needed. However, what if you would like to have the position of the ball for every milli-second of the flight? All that punching on the calculator would have taken you something like four hours! If you know how to program, however, you could modify the code above slightly, using a minute or two of writing, and easily get all the positions computed in one go within a second. A much stronger argument, however, is that mathematical models from real life are often complicated and comprehensive. The pocket calculator cannot cope with such problems, even not the programmable ones, because their computational power and their programming tools are far too weak compared to what a real computer can offer.

Why you must use a text editor to write programs

When Python interprets some code in a file, it is concerned with every character in the file, exactly as it was typed in. This makes it troublesome to write the code into a file with word processors like, e.g., Microsoft Word, since such a program will insert extra characters, invisible to us, with information on how to format the text (e.g., the font size and type). Such extra information is necessary for the text to be nicely formatted for the human eye. Python, however, will be much annoyed by the extra characters in the file inserted by a word processor. Therefore, it is fundamental that you write your program in a text editor where what you type on the keyboard is exactly the characters that appear in the file and that Python will later read. There are many text editors around. Some are stand-alone programs like Emacs, Vim, Gedit, Notepad++, and TextWrangler. Others are integrated in graphical development environments for Python, such as Spyder. This book will primarily refer to Spyder and its text editor.

Installation of Python

You will need access to Python and several add-on packages for doing mathematical computations and display graphics. An obvious choice is to install a Python environment for scientific computing on your machine. Alternatively, you can use cloud services for running Python, or you can remote login on a computer system at a school or university. Available and recommended techniques for getting access to Python and the needed packages are documented in Appendix: Getting access to Python.

The quickest way to get started with a Python installation for this book on your Windows, Mac, or Linux computer, is to install Anaconda.

Write and run your first program

Reading only does not teach you computer programming: you have to program yourself and practice heavily before you master mathematical problem solving via programming. Therefore, it is crucial at this stage that you write and run a Python program. We just went through the program ball.py above, so let us next write and run that code.

But first a warning: there are many things that must come together in the right way for ball.py to run correctly on your computer. There might be problems with your Python installation, with your writing of the program (it is very easy to introduce errors!), or with the location of the file, just to mention some of the most common difficulties for beginners. Fortunately, such problems are solvable, and if you do not understand how to fix the problem, ask somebody. Typically, once you are beyond these common start-up problems, you can move on to learn programming and how programs can do a lot of otherwise complicated mathematics for you.

We describe the first steps using the Spyder graphical user interface (GUI), but you can equally well use a standard text editor for writing the program and a terminal window (Terminal on Mac, Power Shell on Windows) for running the program. Start up Spyder and type in each line of the program ball.py shown earlier. Then run the program. More detailed descriptions of operating Spyder are found in How to write and run a Python program.

If you have had the necessary luck to get everything right, you should now get the number \( 1.2342 \) out in the rightmost lower window in the Spyder GUI. If so, congratulations! You have just executed your first self-written computer program in Python, and you are ready to go on studying this book! You may like to save the program before moving on (File, save as).