Main site of science textbooks
Crowdfunding site for the free
online science textbooks project

Python programming
Dr. Jay Maron


Installing python on a Mac

Python can be downloaded from https://www.python.org/downloads

You will also want to install the following numerical and plotting libraries.

Numpy        http://www.numpy.org
Matplotlib   http://matplotlib.org/downloads.html
Scipy        http://www.scipy.org/scipylib/download.html

Installing python on the Windows 10 bash environment

To install bash, first make sure that you have installed the Windows 10 Aniversary Update.

Instructions for installing bash on Windows 10.

Python is included in bash but it includes few libraries. "math" is one of the only ones. To install more libraries, type:

> sudo apt-get install python-numpy
> sudo apt-get install python-scipy
> sudo apt-get install python-matplotlib

To remove a library type:

> sudo apt-get autoremove python-numpy


Interactive session

To start python, open a terminal and type "python". From here you can type python commands. For example,

>>> print 1. * 2.
2.0
>>> x = 2.
>>> y = 3.
>>> print x*y
6.0
>>> # Anything typed after a "#" is ignored by python
>>> def function(x,y)                  # Define a function
...   function = x*y                   # The content of a function must be indented
...   return function
...                                    # Type "return" to end the function
>>> print function(x,y)
6.0
>>> exit()                             # Exits the python session

Loading and running a program

If you have a file on disk called "program.py", you can load it and run it with

>>> import program as program        # Loads and runs file "program.py"
Once a program has been loaded, it can be reloaded and run by typing
>>> reload(program)
If a program has already been loaded and you type "import program as program", the program will not be run. Running it requires "reload(program)"
Importing libraries

To use a library you have to first import it. For example, to use the numpy library,

>>> import numpy as numpy
>>> print numpy.log(10.)
2.30258509299

                        -----------------------------------
The first few lines of a typical python program usually consists of import statements. The following program imports a comprehensive set of libraries.

#!/usr/bin/env python
import numpy                as numpy
import math                 as math
import pylab                as pylab
import PIL                  as PIL
import os                   as os
import sys                  as sys
import matplotlib           as matplotlib
import matplotlib.pyplot    as plt
import matplotlib.image     as mpimg
import Image                as Image
import matplotlib.animation as animation

Data types
int      Could be int32 or int64.  Depends on the system.
int8     128 to 127
int16    -32768 to 32767
int32    -2147483648 to 2147483647
int64    -9223372036854775808 to 9223372036854775807
uint8    0 to 255
uint16   0 to 65535
uint32   0 to 4294967295
uint64   0 to 18446744073709551615
float    = float64
float16  Half precision float:   sign bit,  5 bits exponent, 10 bits mantissa
float32  Single precision float: sign bit,  8 bits exponent, 23 bits mantissa
float64  Double precision float: sign bit, 11 bits exponent, 52 bits mantissa

>>> i = 1        Defines "i" to be an integer with value "1".
>>> x = 1.       defines "x" to be a float with value "1.".  The "." designates a float
>>> x = 1.e10    Defines "x" to be a float with value 1*10^10

Pass by value

Python functions don't change the values of parameters passed to them. For example,

>>> def zzz(x):
...   x = x + 1.
... 
>>> x = 2.
>>> zzz(x)
>>> print x
2.0

Plotting program
def plot1():
  plt.close()
  fig  = plt.figure(figsize=(10,10),dpi=100,facecolor='black')   # 10x10 inches, 100 dpi
  axes = fig.add_axes([.05,.05,.95,.95])
  axes.xaxis.set_visible(True);axes.set_xlim([0.,1.])
  axes.yaxis.set_visible(True);axes.set_ylim([0.,1.])
  im = Image.new("RGB",(1000,1000),"white")
  x = numpy.zeros([21],float)
  y = numpy.zeros([21],float)
  for j in range(0,21):
    x[j] = .05*float(j)
    y[j] = x[j]*x[j]
  axes.plot(x,y,color='green',lw=1,ls='-',marker='',markersize=3)
  axes.plot(x,y,color='blue',lw=1,ls='',marker='o',markersize=10)
  axes.text(.5,.1,'Text',color='green',ha='center',va='center',fontsize=20)
  plt.imshow(im,extent=[0.,1.,0.,1.])
  plt.savefig('plot1.png')

Useful functions
numpy.random.random()                # Generate a random number from 0. to 1.
os.system("ls")                      # Sends the "ls" command to the terminal shell

>>> array = numpy.zeros([2,3],float) # Create an array
>>> numpy.shape(array)               # Obtain dimensions of an array
(2, 3)
>>> numpy.amax(array)                # Maximum element in array
0.0

Image commands
img = Image.open('jupiter.jpg')       # Read image.  3D array of integers from 0 to 255
img = Image.new("RGB",(10,10),"black")# Create image. 3D array of integers from 0 to 255
plt.imshow(img,extent=[0.,1.,0.,1.])  # Plot image
plt.savefig('plot.png')               # Save image
upside_down = img.transpose(FLIP_TOP_BOTTOM)     # Flip image vertically
left_right  = img.transpose(FLIP_LEFT_RIGHT)     # Flip image horizontally

Plot symbols

The "plot" and "scatter" commands have the following marker types:

'.'  =  Point
','  =  Pixel
'o'  =  Circle
'^'  =  Triangle up
'v'  =  Triangle down
'<'  =  Triangle left
'>'  =  Triangle right
'8'  =  Octagon
's'  =  Square
'p'  =  Pentagon
'*'  =  Star
'h'  =  Hexagon 1
'H'  =  Hexagon 2
'+'  =  Plus
'x'  =  x
'D'  =  Diamond
'd'  =  Thin diamond
'|'  =  Vertical line
'-'  =  Horizontal line
''   =  Blank
'$ $'=  Render the string using mathtext
'TICKUP'     =  Tick up
'TICKDOWN'   =  Tick downup
'TICKLEFT'   =  Tick left
'TICKRIGHT'  =  Tick right
'CARETUP'    =  Caret up
'CARETDOWN'  =  Caret downup
'CARETLEFT'  =  Caret left
'CaretRIGHT' =  Caret right

Python can be installed on a Mac (which works smoothly) or Windows machine (clunky). You can also use it on Cloud 9
Main page

Support the free online science textbooks project






© Jason Maron, all rights reserved.