from math import sin, cos x = pi /4 1_val = sin^2( x ) + cos^2( x ) print 1_VAL # Fix 1: pi needs to be imported from the math module before it can be used in the line below. from math import sin, cos, pi x = pi /4 # Fix 2: 1_val is not a valid variable name - it cannot start with a number # Fix 3: raising something to a power is done using **, not ^ # Fix 4: when calling sin or cos, it's name must be followed by the arguments in brackets. If we want to represent $\sin^2(x)$ # in Python, we have to write it like $\sin(x)^2$, i.e. sin(x)**2. val = sin(x)**2 + cos(x)**2 # Fix 5: variable names are case-sensitive in Python. val is not the same as VAL. print val n = 101 # The number of values start = -1.0 end = 1.0 dx = (end-start)/(n-1) # The distance between each value values = [start + i*dx for i in range(n)] print values from numpy import linspace values_numpy = linspace(start, end, n) for v in values_numpy: print "%.2f" % (v) from numpy import * from pylab import * %pylab inline def f(x, t): return exp(-(x-3*t)**2)*sin(3*pi*(x-t)) n = 1000 xarray = linspace(-3, 10, n) for t in [0, 1, 2]: plot(xarray, f(xarray, t), label=r"$t$ = %.1f" % (t)) xlabel(r"$x$") ylabel(r"$f(x,t)$") legend(loc="best") show() from numpy import * f = open("seismic.dat", "r") magnitude = [] for line in f: s = line.split() magnitude.append(float(s[-1])) # The last column is the "magnitude" magnitude = array(magnitude) f.close() print magnitude count = 0 for m in magnitude: if m > 6.0: count += 1 print "There are %d earthquakes above magnitude 6.0" % (count) f = open("human_evolution.txt", "r") humans = {} for line in f: # Ignore lines that don't start with "H." if(line[0:2] != "H."): continue # Get each column and strip out leading and trailing whitespace name = line[0:21].strip() lived = line[21:37].strip() height = line[37:50].strip() mass = line[50:62].strip() brain_volume = line[62:].strip() # Add to dictionary humans[name] = [lived, height, mass, brain_volume] f.close() # Test print humans["H. habilis"] print "%25s %25s %25s %25s %25s" % ("Species", "Lived when (M. years)", "Adult height (m)", "Adult mass (kg)", "Brain volume (cm**3)") for human in humans: data = humans[human] print "%25s %25s %25s %25s %25s" % (human, data[0], data[1], data[2], data[3])