How to ... in Python (in examples)

Assembled by Ross Bannister, University of Reading

Comments

# This is a single line comment
​
’’’
These are (effectively)
multiple line
comments
’’’
​
Shebang at start of python code
#!/usr/bin/env python

Arrays

Create a variable-length array

a = []
a.append (item_a)
a.append (item_b)
...

Create a specific size array (initialised with zeros)

shape = (Nz,Ny,Nx)
array = np.zeros(shape)

Create a specific size array (initialised with something specific)

array = np.repeat(init, N)

Create a sequence

array = range(N)

Averaging over arrays

array_mean = array.mean(axis=2)
# Axis 0 is the first axis

Find the shape of an array

shape            = array.shape
size_of_1d_array = len(1d_array)

Masks for numpy arrays

array        = np.repeat(5.0, N)
array[3]     = 10.0
mask         = (array[:] > 7.0)
array[mask]  = array[mask] / 2.0   # will halve elements satisfying the mask
array[~mask] = array[~mask] * 2.0  # will double elements not satisfying the mask

Loops and other structures

For loop

for lev in range(0,Nz,1):
  print ’This is level ’, lev 

While loop

while condition:
  ...

If branch

if condition:
  ...
else:
  ...

Operators

Mathematical operators

** power
== equal to
!= not equal to
<, <=
>, >=
and, or, not
True, False

Compound assignment operators

variable1 += variable2
is equivalent to:
variable1 = variable1 + variable2;
(similarly for other operators)

Data types

Conversions

string = str(number)
​
string3digits = str(number).zfill(3)
​
map(float, array_of_string_numbers)

Input and output

Formatted output

# E.g. File001.nc, File002.nc, etc.
​
# Output
print ("File03i.nc”% (FileNumber))
​
# Contents of string
Filename = ’File%03i.nc’% (FileNumber) 

ASCII files

Reading

Example with end of file check and extracting column data with split
input_file = open (path + ’/’ + file, ’r’)
line = input_file.readline()
while (line != ’’):
  line  = input_file.readline()
  split = line.split()
  print split[0], split[1], split[2]
input_file.close()

Writing

output_file = open (path + ’/’ + file, ’w’)
output_file.write (string)
output_file.close()

NetCDF files

Reading

nc   = ncfile(path + ’/’ + file)
x    = nc.variables[’dim1’][:]
y    = nc.variables[’dim2’][:]
data = nc.variables[’variable’][:,:]
nc.close()
Nx   = len(x)
Ny   = len(y)

Subroutines

def Name_of_routine (argument1, argument2):
​
...
​
# if this is a function then
  return result
# or if this is not a function then
  return

Plotting

Plot lines to the screen, or to a file

import matplotlib.pyplot as plt
import matplotlib
​
fig, ax = plt.subplots()
​
ax.set_xlabel(’x (km)’, fontsize=16)
ax.set_ylabel(’y (km)’, fontsize=16)
ax.set_ylim([0.0, 30.0])
​
plt.title(’Title of plot’, fontsize=16)
​
# Plot a couple of lines and a scatter
# Can first set the tick label font sizes
matplotlib.rc(’xtick’, labelsize=16)
matplotlib.rc(’ytick’, labelsize=16) 
ax.plot(x[:], y1[:], linewidth=2, color=’red’, label=’line 1’)
ax.plot(x[:], y2[:], linewidth=2, color=’green’, label=’line 2’)
plt.scatter(x[:], y3[:]) 
# Plot an errorbar
ax.errorbar(x[:], y4[:], yerr=errbar[:], color=’blue’, linewidth=2)
​
# Plot two lines and fill between them (e.g. plot between 0.0 and y4)
ax.fill_between(x[:], 0.0, y5[:], color=’lightblue’, label=’Filled’)
​
# Show the legend
ax.legend()
​
plt.show()             # Comment out to not display plot on the screen
plt.savefig(filename)  # Comment out to not save the file
plt.close(’all’)
​
​
# Plot filled contours of a field
matplotlib.rc(’xtick’, labelsize=16)
matplotlib.rc(’ytick’, labelsize=16)
fig, ax = plt.subplots()
cmap = cm.get_cmap(’seismic’, 11)
cax  = ax.contourf(xvalues, yvalues, field, cmap=cmap)
cbar = fig.colorbar(cax, orientation=’vertical’, cmap=cmap)
cax  = ax.contour(longs_v, full_level, field, colors=’k’)
# Labels etc
ax.set_title(’Plot title’, fontsize=16)
ax.set_xlabel(’x-axis label’, fontsize=16)
ax.set_ylabel(’y-axis label’, fontsize=16)
plt.show()
plt.savefig(’filename.eps’, bbox_inches=’tight’)
plt.close(’all’)
​
​
# Plot an image
fig, ax = plt.subplots()
cax     = ax.imshow(field, interpolation=’None’, cmap=’seismic’,
                    extent=extent, vmin=minvalue, vmax=maxvalue)
cbar    = fig.colorbar(cax, orientation=’vertical’)
ax.set_title(’Plot title’)
ax.set_xlabel(’x-axis label’, fontsize=16)
ax.set_ylabel(’y-axis label’, fontsize=16)
#plt.show()
plt.savefig(plotdir + ’/cov_rbalrbal.eps’, bbox_inches=’tight’)
plt.close(’all’)

Log-scale plots

Add the following before the plot command
ax.set_xscale(’log’)

Alternative way of changing font size

for item in ([ax.title, ax.xaxis.label, ax.yaxis.label] +
             ax.get_xticklabels() + ax.get_yticklabels()):
  item.set_fontsize(10) 

Miscellaneous

Exiting on command

exit()

Not a number

numpy.nan

Operating system call

import os
os.system("shell_command")