Computational Methods in Physics ASU Physics PHY 494

02 The first Python program

In your work directory, create a directory ~/PHY494/02_python and go to this directory:

mkdir ~/PHY494/02_python
cd ~/PHY494/02_python

Hello World

Using you favorite editor (for instance, atom), create a text file named hello.py in the directory ~/PHY494/02_python1 with the following content:

# hello world in Python

name = input("What's your name? --> ")
print("Hello ", name, ", it's great to see you here.")

Execute ("run") your hello.py program with the python program:

python hello.py

It should ask you for your name: type it and hit Enter. You should be greeted nicely with a message on your screen.

  • The line starting with # is a comment and Python ignores everything on the line starting with the comment character.
  • Blank lines are ignored.
  • name is a variable: it stores a value (more later); variable names are arbitrary (as long as you only use letters, numbers, underscore, don't start with a number, and don't use a name that is already used by Python)
  • input() and print() are functions: they take values as input and do something with it (more later).

Python interpreter

Python is an interpreted language; you can think of python reading each line in an input file and executing it. Start python on its own:

python

You should see something like

 Python 3.5.3 |Anaconda custom (x86_64)| (default, Mar  6 2017, 12:15:08)
 [GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)] on darwin
 Type "help", "copyright", "credits" or "license" for more information.
 >>>

The Python prompt is >>>.

Type commands and execute them with Enter. Like the shell, Python is a REPL, a "Read-eval-print-loop". For example, to add two numbers

>>> 41 + 1
42
>>> 1.5 + 5e-1
2.0

Exit with quit() or Ctrl + d.

Help!

In Python you can often get help by saying

>>> help()
>>> help("something")

For example, get help on the addition operator (and much more):

>>> help("+")

Activity: Python as a calculator

Start python and figure out 2 how to compute the left hand sides (the right hand sides are there for you to check your results):

\begin{align} -1 + 2 &= 1\\ 102 - 201 &= -99\\ 12345678987654321 \times 9876543210123456789 &= 121932631979881115785550983112635269\\ 3/2 &= 1.5\\ \frac{1}{1 - 0.9^2} &= 5.263157894736843\\ 1 + \frac{2}{1} + \frac{2^2}{1\cdot2} + \frac{2^3}{1\cdot2\cdot3} + \frac{2^4}{1 \cdot 2\cdot3\cdot4} &= 7.0\\ -3^4 &= -81\\ 2 - 5.5\times 10^{-7} &= 1.99999945\\ 1.672621898\times 10^{-27} \times (3\times10^8)^2 &= 1.5053597082 \times 10^{-10}\\ \sqrt{2} &= 1.4142135623730951\\ \sqrt{-1} &= i\\ (1 + 2i) + (-2 + i) &= -1 + 3i\\ \frac{1 + 2i}{2 - i} &= i\\ \end{align}

More operations

  • floor division ("integer division") // 3
  • remainder %
>>> 13 / 3  # division returns a float
4.333333333333333
>>> 13 // 3  # floor division discards the fractional part
4
>>> 13 % 3  # the % operator returns the remainder of the division
1
>>> 4 * 3 + 1  # result * divisor + remainder
13

Potential problems…

Division by zero raises an error (an "exception"):

>>> 1/0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero

Floating point numbers are not real real numbers (more later): calculating in Python

>>> 10 + 1e-16
10.0

does not give the expected answer!

Activity: hello, line by line

Type the commands from hello.py into the interpreter, hitting Enter after every line, and execute your program step by step.

Basic plotting

Create a file motion.py with content

# plot motion with constant acceleration

import matplotlib.pyplot as plt

a = 1.0    # acceleration
v0 = 0.0   # initial velocity

t, h, n = 0.0, 0.1, 20    # init time, step size, number of steps
ta, xa = [], []           # time and position lists

for i in range(n):
    x = v0*t + a*t*t/2.0
    ta.append(t)
    xa.append(x)
    t = t + h

# plot results
plt.figure(figsize=(4, 4))
plt.plot(ta, xa, '-o', color="red", linewidth=2)
plt.xlabel("t (s)")
plt.ylabel("x (m)")

plt.savefig("motion.png")
plt.show()

You should create a graph similar to the following:

Constant acceleration plot

Interactive Python with ipython

The ipython interpreter is like python but with lots of improvements such as TAB-completion, help with command? (one question mark directly following a command) and source code with command?? (two question marks), command line history, and many additional shell-like commands (so-called "magic" commands such as %cd, %ls, %pwd, %run, %time and %timeit — see %magic for help).

Start it with

ipython

It should look like

Python 3.5.3 |Anaconda custom (x86_64)| (default, Mar  6 2017, 12:15:08)
Type 'copyright', 'credits' or 'license' for more information
IPython 6.1.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]:

where In [1]: is the prompt.

Just use ipython instead of python for interactive work.

ipython basics

  • To exit, give the exit() command or ^D (Control + D).
  • Use arrow keys to move up and down through the history or through multi-line commands.
  • Use TAB-completion.
  • Use command? or ?command (question mark directly before or after a command or object) to get help
  • %run FILE executes FILE similarly to python FILE.4

ipython with matplotlib

In the basic plotting example we used the matplotlib library for plotting and wrote a figure to a file. ipython can show figures interactively but the details depend on your operating system and installed packages. Try the following and see if the figure is displayed on your screen when you run motion.py: 5

Windows

Run ipython qtconsole to show graphics inline:

ipython qtconsole

In ipython 4

%run motion.py

macOS

Run ipython

ipython --matplotlib=osx

In ipython 4

%run motion.py

Linux

Run ipython

ipython --matplotlib=gtk3

(If gtk3 does not work, try qt5, qt, wx, tk, auto, or just --matplotlib.)

In ipython 4

%run motion.py

Footnotes

  1. If you can call your editor from the command line then this is as easy as, for example with atom (or nano),

     cd ~/PHY494/02_python
     atom hello.py
    

    This will open a new file with name hello.py or open an existing file if it is present.

    However, if you use an editor that you have to open from, say, the Windows Start menu, then you need to first open the editor and then use a menu command such as File → New to create a blank document (use or File → Open to open an existing file). Once you have written content you need to save it in the correct location (usually, or File → Save). To find the 02_python directory, first navigate to your home directory:

    • This can be tricky on Windows : In your shell (not in your editor), type cd; pwd to learn the path to your home directory. In your editor's file system dialog window, start from the system disk (normally C: under Computer) and look for C:\Users\YOUR_USERNAME.

    • On Apple Mac OS X, your home directory is /Users/YOUR_USERNAME.

    • On typical Linux distributions it is /home/YOUR_USERNAME.

    In your home directory, locate the PHY494 folder, click on it to find the 02_python folder inside and click on the latter. Provide the file name ("hello.py") and save the file. (In the shell, make sure that the file is in place where you expect it to be, i.e., ls -la.) 

  2. If you need help, look at Using Python as a Calculator in the standard Python Tutorial. 

  3. In Python 2, the / division operator would perform floor division if both operands were integers but normal ("true") division if at least one operand was a floating point number. Therefore, in old Python 2 code you might see constructs such as 1.0 * a / 2 to force a true division, no matter the value of the variable a. In Python 3, the / operator always performs true division, which prevents some rather nasty bugs from occuring. 

  4. %run is an ipython "magic" command, see help on those commands with %magic 2 3 4

  5. If you don't want to see graphics inline but as a separate window you can try

    ipython --matplotlib=qt5
    

    (If qt5 does not work, try qt, wx, tk, auto, or just --matplotlib.)

    However, this does not always work and might require additional packages. Please share any insights and solutions!