t = 0.5 v0 = 2 a = 0.2 s = v0*t + 0.5*a*t**2 print s t = 0.5 # real number makes float object v0 = 2 # integer makes int object a = 0.2 # float object s = v0*t + 0.5*a*t**2 # float object print 's=%g' % s # g: compact notation print 's=%.2f' % s # f: decimal notation, .2f: 2 decimals print 's={s:.2f}'.format(s=s) v0 = 2 a = 0.2 dt = 0.1 # Increment t = 0 # Start value while t <= 2: s = v0*t + 0.5*a*t**2 print t, s t = t + dt while condition: a = 0 da = 0.4 while a <= 1.2: print a a = a + da a = 0 da = 0.4 while a <= 1.2: print a a = a + da # Inspect all decimals in da and a print 'da=%.16E\na=%.16E' % (da, a) print 'a <= 1.2: %g' % (a <= 1.2) a = 1.2 b = 0.4 + 0.4 + 0.4 boolean_condition1 = a == b # may be False # This is the way to do it tol = 1E-14 boolean_condition2 = abs(a - b) < tol # True L = [-1, 1, 8.0] L = ['mydata.txt', 3.14, 10] # string, float, int L = ['mydata.txt', 3.14, 10] print L[0] # print first element (index 0) print L[1] # print second element (index 1) del L[0] # delete the first element print L print len(L) # length of L L.append(-1) # add -1 at the end of the list print L v0 = 2 a = 0.2 dt = 0.1 # Increment t = 0 t_values = [] s_values = [] while t <= 2: s = v0*t + 0.5*a*t**2 t_values.append(t) s_values.append(s) t = t + dt print s_values # Just take a look at a created list # Print a nicely formatted table i = 0 while i <= len(t_values)-1: print '%.2f %.4f' % (t_values[i], s_values[i]) i += 1 # Same as i = i + 1 L = [1, 4, 8, 9] for e in L: print e list1 = [0, 0.1, 0.2] list2 = [] for element in list1: p = element + 2 list2.append(p) print list2 somelist = ['file1.dat', 22, -1.5] for i in range(len(somelist)): # access list element through index print somelist[i] v0 = 2 a = 0.2 dt = 0.1 # Increment t_values = [] s_values = [] n = int(round(2/dt)) + 1 # No of t values for i in range(n): t = i*dt s = v0*t + 0.5*a*t**2 t_values.append(t) s_values.append(s) print s_values # Just take a look at a created list # Make nicely formatted table for t, s in zip(t_values, s_values): print '%.2f %.4f' % (t, s) # Alternative implementation for i in range(len(t_values)): print '%.2f %.4f' % (t_values[i], s_values[i]) for e1, e2, e3, ... in zip(list1, list2, list3, ...): for i in range(len(list1)): e1 = list1[i] e2 = list2[i] e3 = list3[i] ... import numpy L = [1, 4, 10.0] # List of numbers a = numpy.array(L) # Convert to array print a print a[1] # Access element through indexing print a[0:2] # Extract slice (index 2 not included!) print a.dtype # Data type of an element b = 2*a + 1 # Can do arithmetics on arrays print b c = numpy.log(a) print c t = numpy.linspace(a, b, n+1) t = numpy.zeros(n) s = numpy.zeros_like(t) # zeros with t's size and data type import numpy v0 = 2 a = 0.2 dt = 0.1 # Increment n = int(round(2/dt)) + 1 # No of t values t_values = numpy.linspace(0, 2, n+1) s_values = v0*t + 0.5*a*t**2 # Make nicely formatted table for t, s in zip(t_values, s_values): print '%.2f %.4f' % (t, s) import math print math.sin(math.pi) from math import sin, pi print sin(pi) # Or import everything from math from math import * print sin(pi), log(e), tanh(0.5) from numpy import * x = linspace(0, 1, 101) y = exp(-x)*sin(pi*x) import numpy as np x = np.linspace(0, 1, 101) y = np.exp(-x)*np.sin(np.pi*x) import numpy as np x = np.linspace(0, 1, 101) from numpy import sin, exp, pi y = exp(-x)*sin(pi*x) a = np.linspace(1, 5, 5) b = a >>> a array([ 1., 2., 3., 4., 5.]) >>> b[0] = 5 # changes a[0] to 5 >>> a array([ 5., 2., 3., 4., 5.]) >>> a[1] = 9 # changes b[1] to 9 >>> b array([ 5., 9., 3., 4., 5.]) >>> c = a.copy() # copy all elements to new array c >>> c[0] = 6 # a is not changed >>> a array([ 1., 2., 3., 4., 5.]) >>> c array([ 6., 2., 3., 4., 5.]) >>> b array([ 5., 2., 3., 4., 5.]) import numpy as np N = 6 diagonals = np.zeros((3, N)) # 3 diagonals import scipy.sparse A = scipy.sparse.spdiags(diagonals, [-1,0,1], N, N, format='csc') A.toarray() # look at corresponding dense matrix diagonals = [-np.linspace(1, N, N)[0:-1], -2*np.ones(N), np.linspace(1, N, N)[1:]] # 3 diagonals A = scipy.sparse.diags(diagonals, [-1,0,1], format='csc') A.toarray() # look at corresponding dense matrix B = scipy.sparse.diags([1, 2, 3], [-2, 0, 1], shape=(6, 6), format='csc') B.toarray() # look at corresponding dense matrix x = np.linspace(-1, 1, N) # choose solution b = A.dot(x) # sparse matrix vector product import scipy.sparse.linalg x = scipy.sparse.linalg.spsolve(A, b) print x A_d = A.toarray() # corresponding dense matrix b = np.dot(A_d, x) # standard matrix vector product x = np.linalg.solve(A_d, b) # standard Ax=b algorithm print x %matplotlib inline import numpy as np import matplotlib.pyplot as plt v0 = 0.2 a = 2 n = 21 # No of t values for plotting t = np.linspace(0, 2, n+1) s = v0*t + 0.5*a*t**2 plt.plot(t, s) plt.savefig('myplot.png') plt.show() import numpy as np import matplotlib.pyplot as plt v0 = 0.2 n = 21 # No of t values for plotting t = np.linspace(0, 2, n+1) a = 2 s0 = v0*t + 0.5*a*t**2 a = 3 s1 = v0*t + 0.5*a*t**2 plt.plot(t, s0, 'r-', # Plot s0 curve with red line t, s1, 'bo') # Plot s1 curve with blue circles plt.xlabel('t') plt.ylabel('s') plt.title('Distance plot') plt.legend(['$s(t; v_0=2, a=0.2)$', '$s(t; v_0=2, a=0.8)$'], loc='upper left') plt.savefig('myplot.png') plt.show() def s(t): return v0*t + 0.5*a*t**2 v0 = 0.2 a = 4 value = s(3) # Call the function def s(t, v0, a): return v0*t + 0.5*a*t**2 value = s(3, 0.2, 4) # Call the function # More readable call value = s(t=3, v0=0.2, a=4) def s(t, v0=1, a=1): return v0*t + 0.5*a*t**2 value = s(3, 0.2, 4) # specify new v0 and a value = s(3) # rely on v0=1 and a=1 value = s(3, a=2) # rely on v0=1 value = s(3, v0=2) # rely on a=1 value = s(t=3, v0=2, a=2) # specify everything value = s(a=2, t=3, v0=2) # any sequence allowed def s(t, v0, a): return v0*t + 0.5*a*t**2 for i in range(len(t)): s_values[i] = s(t_values[i], v0, a) s_values = s(t_values, v0, a) from math import exp, sin def f(x): return 2*x + x**2*exp(-x)*sin(x) v = f(4) # f(x) works with scalar x # Redefine exp and sin with their vectorized versions from numpy import exp, sin, linspace x = linspace(0, 4, 100001) v = f(x) # f(x) works with array x def movement(t, v0, a): s = v0*t + 0.5*a*t**2 v = v0 + a*t return s, v s_value, v_value = movement(t=0.2, v0=2, a=4) def f(x): return x+1, x+2, x+3 r = f(3) # Store all three return values in one object r print r type(r) # What type of object is r? print r[1] if condition: else: if t <= t1: s = v0*t + 0.5*a0*t**2 else: s = v0*t + 0.5*a0*t1**2 + a0*t1*(t-t1) if condition1: elif condition2: elif condition3: else: if condition: def s_func(t, v0, a0, t1): if t <= t1: s = v0*t + 0.5*a0*t**2 else: s = v0*t + 0.5*a0*t1**2 + a0*t1*(t-t1) return s def f(x): return x if x < 1 else 2*x import numpy as np x = np.linspace(0, 2, 5) f(x) n = 201 # No of t values for plotting t1 = 1.5 t = np.linspace(0, 2, n+1) s = np.zeros(n+1) for i in range(len(t)): s[i] = s_func(t=t[i], v0=0.2, a0=20, t1=t1) plt.plot(t, s, 'b-') plt.plot([t1, t1], [0, s_func(t=t1, v0=0.2, a0=20, t1=t1)], 'r--') plt.xlabel('t') plt.ylabel('s') plt.savefig('myplot.png') plt.show() s = np.where(condition, s1, s2) s = np.where(t <= t1, v0*t + 0.5*a0*t**2, v0*t + 0.5*a0*t1**2 + a0*t1*(t-t1)) s = np.zeros_like(t) # Make s as zeros, same size & type as t s[t <= t1] = (v0*t + 0.5*a0*t**2)[t <= t1] s[t > t1] = (v0*t + 0.5*a0*t1**2 + a0*t1*(t-t1))[t > t1] infile = open('.input.dat', 'r') for line in infile: # Typical line: variable = value variable, value = line.split('=') variable = variable.strip() # remove leading/traling blanks if variable == 'v0': v0 = float(value) elif variable == 'a': a = float(value) elif variable == 'dt': dt = float(value) elif variable == 'interval': interval = eval(value) infile.close() line = 'v0 = 5.3' variable, value = line.split('=') variable value variable.strip() # strip away blanks obj1 = eval('1+2') # Same as obj1 = 1+2 obj1, type(obj1) obj2 = eval('[-1, 8, 10, 11]') obj2, type(obj2) from math import sin, pi x = 1 obj3 = eval('sin(pi*x)') obj3, type(obj3) import sys command_line_expression = sys.argv[1] from math import * # Define sin, cos, exp, pi, etc. result = eval(command_line_expression) print result with open('.input.dat', 'r') as infile: for line in infile: ... outfile = open('table1.dat', 'w') outfile.write('# t s(t)\n') # write table header for t, s in zip(t_values, s_values): outfile.write('%.2f %.4f\n' % (t, s)) import numpy as np # Make two-dimensional array of [t, s(t)] values in each row data = np.array([t_values, s_values]).transpose() # Write data array to file in table format np.savetxt('table2.dat', data, fmt=['%.2f', '%.4f'], header='t s(t)', comments='# ') data = np.loadtxt('table2.dat', comments='#') class Trivial: def __init__(self, a): self.a = a def dump(self): print self.a t = Trivial(a=4) t.dump() s = Distance(v0=2, a=0.5) # create instance v = s(t=0.2) # compute formula class Distance: def __init__(self, v0, a): self.v0 = v0 self.a = a def __call__(self, t): v0, a = self.v0, self.a # make local variables return v0*t + 0.5*a*t**2 s = Distance(v0=2, a=0.5) # create instance v = s(t=0.2) # actually s.__call__(t=0.2) class F: def __init__(self, p1, p2, ...): self.p1 = p1 self.p2 = p2 ... def __call__(self, x, y, z): # return formula involving x, y, z and self.p1, self.p2 ... f = F(p1=..., p2=..., ...) # create instance with parameters print f(1, 4, -1) # evaluate f(x,y,z) function