$$ \newcommand{\tp}{\thinspace .} $$

This chapter is taken from the book A Primer on Scientific Programming with Python by H. P. Langtangen, 5th edition, Springer, 2016.

Interactive computing

A particular convenient feature of Python is the ability to execute statements and evaluate expressions interactively. The environments where you work interactively with programming are commonly known as Python shells. The simplest Python shell is invoked by just typing python at the command line in a terminal window. Some messages about Python are written out together with a prompt >>>, after which you can issue commands. Let us try to use the interactive shell as a calculator. Type in 3*4.5-0.5 and then press the Return key to see Python's response to this expression:

Terminal> python
Python 2.7.5+ (default, Sep 19 2013, 13:48:49)
[GCC 4.8.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 3*4.5-0.5
13.0
The text on a line after >>> is what we write (shell input) and the text without the >>> prompt is the result that Python calculates (shell output). It is easy, as explained below, to recover previous input and edit the text. This editing feature makes it convenient to experiment with statements and expressions.

Using the Python shell

The program from the section Using variables can be typed in line by line in the interactive shell:

>>> v0 = 5
>>> g = 9.81
>>> t = 0.6
>>> y = v0*t - 0.5*g*t**2
>>> print y
1.2342
We can now easily calculate an y value corresponding to another (say) v0 value: hit the up arrow key to recover previous statements, repeat pressing this key until the v0 = 5 statement is displayed. You can then edit the line, e.g., to

>>> v0 = 6
Press return to execute this statement. You can control the new value of v0 by either typing just v0 or print v0:

>>> v0
6
>>> print v0
6
The next step is to recompute y with this new v0 value. Hit the up arrow key multiple times to recover the statement where y is assigned, press the Return key, and write y or print y to see the result of the computation:

>>> y = v0*t - 0.5*g*t**2
>>> y
1.8341999999999996
>>> print y
1.8342
The reason why we get two slightly different results is that typing just y prints out all the decimals that are stored in the computer (16), while print y writes out y with fewer decimals. As mentioned in the section A first glimpse of rounding errors computations on a computer often suffer from rounding errors. The present calculation is no exception. The correct answer is 1.8342, but rounding errors lead to a number that is incorrect in the 16th decimal. The error is here \( 4\cdot 10^{-16} \).

Type conversion

Often you can work with variables in Python without bothering about the type of objects these variables refer to. Nevertheless, we encountered a serious problem in the section Potential error: integer division with integer division, which forced us to be careful about the types of objects in a calculation. The interactive shell is very useful for exploring types. The following example illustrates the type function and how we can convert an object from one type to another.

First, we create an int object bound to the name C and check its type by calling type(C):

>>> C = 21
>>> type(C)
<type 'int'>
We convert this int object to a corresponding float object:

>>> C = float(C)   # type conversion
>>> type(C)
<type 'float'>
>>> C
21.0
In the statement C = float(C) we create a new object from the original object referred to by the name C and bind it to the same name C. That is, C refers to a different object after the statement than before. The original int with value 21 cannot be reached anymore (since we have no name for it) and will be automatically deleted by Python.

We may also do the reverse operation, i.e., convert a particular float object to a corresponding int object:

>>> C = 20.9
>>> type(C)
<type 'float'>
>>> D = int(C)      # type conversion
>>> type(D)
<type 'int'>
>>> D
20                  # decimals are truncated :-/
In general, one can convert a variable v to type MyType by writing v=MyType(v), if it makes sense to do the conversion.

In the last input we tried to convert a float to an int, and this operation implied stripping off the decimals. Correct conversion according to mathematical rounding rules can be achieved with help of the round function:

>>> round(20.9)
21.0
>>> int(round(20.9))
21

IPython

There exist several improvements of the standard Python shell presented in the section Interactive computing. The author advocates IPython as the preferred interactive shell. You will then need to have IPython installed. Typing ipython in a terminal window starts the shell. The (default) prompt in IPython is not >>> but In [X]:, where X is the number of the present input command. The most widely used features of IPython are summarized below.

Running programs

Python programs can be run from within the shell:

In [1]: run ball2.py
1.2342
This command requires that you have taken a cd to the folder where the ball2.py program is located and started IPython from there.

On Windows you may, as an alternative to starting IPython from a DOS or PowerShell window, double click on the IPython desktop icon or use the Start menu. In that case, you must move to the right folder where your program is located. This is done by the os.chdir (change directory) command. Typically, you write something like

In [1]: import os
In [2]: os.chdir(r'C:\Documents and Settings\me\My Documents\div')
In [3]: run ball2.py
if the ball2.py program is located in the folder div under My Documents of user me. Note the r before the quote in the string: it is required to let a backslash really mean the backslash character. If you end up typing the os.chdir command every time you enter an IPython shell, this command (and others) can be placed in a startup file such that they are automatically executed when you launch IPython.

Inside IPython you can invoke any operating system command. This allows us to navigate to the right folder above using Unix or Windows (cd) rather than Python (os.chdir):

In [1]: cd C:\Documents and Settings\me\My Documents\div
In [3]: run ball2.py

We recommend running all your Python programs from the IPython shell. Especially when something goes wrong, IPython can help you to examine the state of variables so that you become quicker to locate bugs.

Typesetting convention for executing Python programs.

In the rest of the document, we just write the program name and the output when we illustrate the execution of a program:

ball2.py
1.2342
You then need to write run before the program name if you execute the program in IPython, or if you prefer to run the program directly in a terminal window, you need to write python prior to the program name. The document Different ways of running Python programs [2] describes various other ways to run a Python program.

Quick recovery of previous output

The results of the previous statements in an interactive IPython session are available in variables of the form _iX (underscore, i, and a number X), where X is 1 for the last statement, 2 for the second last statement, and so forth. Short forms are _ for _i1, __ for _i2, and ___ for _i3. The output from the In [1] input above is 1.2342. We can now refer to this number by an underscore and, e.g., multiply it by 10:

In [2]: _*10
Out[2]: 12.341999999999999
Output from Python statements or expressions in IPython are preceded by Out[X] where X is the command number corresponding to the previous In [X] prompt. When programs are executed, as with the run command, or when operating system commands are run (as shown below), the output is from the operating system and then not preceded by any Out[X] label.

The command history from previous IPython sessions is available in a new session. This feature makes it easy to modify work from a previous session by just hitting the up-arrow to recall commands and edit them as necessary.

Tab completion

Pressing the TAB key will complete an incompletely typed variable name. For example, after defining my_long_variable_name = 4, write just my at the In [4]: prompt below, and then hit the TAB key. You will experience that my is immediately expanded to my_long_variable_name. This automatic expansion feature is called TAB completion and can save you from quite some typing.

In [3]: my_long_variable_name = 4

In [4]: my_long_variable_name
Out[4]: 4

Recovering previous commands

You can walk through the command history by typing Ctrl+p or the up arrow for going backward or Ctrl+n or the down arrow for going forward. Any command you hit can be edited and re-executed. Also commands from previous interactive sessions are stored in the command history.

Running Unix/Windows commands

Operating system commands can be run from IPython. Below we run the three Unix commands date, ls (list files), mkdir (make directory), and cd (change directory):

In [5]: date
Thu Nov 18 11:06:16 CET 2010

In [6]: ls
myfile.py  yourprog.py

In [7]: mkdir mytestdir

In [8]: cd mytestdir
If you have defined Python variables with the same name as operating system commands, e.g., date=30, you must write !date to run the corresponding operating system command.

IPython can do much more than what is shown here, but the advanced features and the documentation of them probably do not make sense before you are more experienced with Python - and with reading manuals.

Typesetting of interactive shells in this document.

In the rest of the document we will apply the >>> prompt in interactive sessions instead of the input and output prompts as used by default by IPython, simply because most Python books and electronic manuals use >>> to mark input in interactive shells. However, when you sit by the computer and want to use an interactive shell, we recommend using IPython, and then you will see the In [X] prompt instead of >>>.

Notebooks

A particularly interesting feature of IPython is the notebook, which allows you to record and replay exploratory interactive sessions with a mix of text, mathematics, Python code, and graphics. See the document How to access Python for doing scientific computing [1] for a quick introduction to IPython notebooks.