v0 = 5 g = 9.81 t = 0.6 y = v0*t - 0.5*g*t**2 print y C = 21; F = (9.0/5)*C + 32; print F C = raw_input('C=? ') # C becomes a string C = float(C) # convert to float so we can compute F = (9./5)*C + 32 print F n = int(raw_input('n=? ')) for i in range(2, 2*n+1, 2): print i # or: print range(2, 2*n+1, 2) # or: for i in range(1, n+1): print 2*i C = 21; F = (9.0/5)*C + 32; print F # Need to fill in sys.argv for use in the notebook import sys sys.argv[1] = '21' import sys C = float(sys.argv[1]) # read 1st command-line argument F = 9.0*C/5 + 32 print F s = '1+2' r = eval(s) r type(r) r = eval('[1, 6, 7.5] + [1, 2]') r type(r) r = eval('math programming') r = math programming s = "'math programming'" r = eval(s) r i1 = eval(raw_input('Give input: ')) i2 = eval(raw_input('Give input: ')) r = i1 + i2 print '%s + %s becomes %s\nwith value %s' % \ (type(i1), type(i2), type(r), r) statement = 'r = 1+1' # store statement in a string exec(statement) print r # prints 2 somecode = ''' def f(t): term1 = exp(-a*t)*sin(w1*x) term2 = 2*sin(w2*x) return term1 + term2 ''' exec(somecode) # execute the string as Python code formula = raw_input('Write a formula involving x: ') code = """ def f(x): return %s """ % formula from math import * # make sure we have sin, cos, log, etc exec(code) # turn string formula into live function # Ask the user for x values and evaluate f(x) x = 0 while x is not None: x = eval(raw_input('Give x (None to quit): ')) if x is not None: y = f(x) print 'f(%g)=%g' % (x, y) from scitools.std import StringFunction formula = 'exp(x)*sin(x)' f = StringFunction(formula) f(0) from math import pi f(pi) print str(f) g = StringFunction('A*exp(-a*t)*sin(omega*x)', independent_variable='t', A=1, a=0.1, omega=pi, x=5) print g(1.2) g.set_parameters(A=2, x=10) print g(1.2) from Tkinter import * root = Tk() C_entry = Entry(root, width=4) C_entry.pack(side='left') Cunit_label = Label(root, text='Celsius') Cunit_label.pack(side='left') def compute(): C = float(C_entry.get()) F = (9./5)*C + 32 F_label.configure(text='%g' % F) compute = Button(root, text=' is ', command=compute) compute.pack(side='left', padx=4) F_label = Label(root, width=4) F_label.pack(side='left') Funit_label = Label(root, text='Fahrenheit') Funit_label.pack(side='left') root.mainloop() f = open('data.txt', 'w') f.write("""21.8 18.1 19 23 26 17.8 """) f.close() infile = open('data.txt', 'r') # open file mean = 0 for line in infile: number = float(line) # line is string mean = mean + number print 'number=%g' % g mean = mean/len(lines) print mean f = open('tmp.txt', 'w') f.write("""Line 1. Line 2. Line 3. Line 4. """) f.close() infile = open('tmp.txt', 'r') lines = infile.readlines() # read all lines lines infile.readline() # no more to read infile = open('tmp.txt', 'r') infile.readline() # read one line infile.readline() # read next line for line in infile: # read the next lines to the end print line infile = open('tmp.txt', 'r') filestr = infile.read() filestr filestr.split() # split out all words line = 'Line 3.\n' line.split() line.split('e') f = open('rainfall.txt', 'w') f.write("""Average rainfall (in mm) in Rome: 1188 months between 1782 and 1970 Jan 81.2 Feb 63.2 Mar 70.3 Apr 55.7 May 53.0 Jun 36.4 Jul 17.5 Aug 27.5 Sep 60.9 Oct 117.7 Nov 111.0 Dec 97.9 Year 792.9 """) f.close() line = 'Oct 117.7' words = line.split() words type(words[1]) # string, not a number! def extract_data(filename): infile = open(filename, 'r') infile.readline() # skip the first line months = [] rainfall = [] for line in infile: words = line.split() # words[0]: month, words[1]: rainfall months.append(words[0]) rainfall.append(float(words[1])) infile.close() months = months[:-1] # Drop the "Year" entry annual_avg = rainfall[-1] # Store the annual average rainfall = rainfall[:-1] # Redefine to contain monthly data return months, rainfall, annual_avg months, values, avg = extract_data('rainfall.dat') print 'The average rainfall for the months:' for month, value in zip(months, values): print month, value print 'The average rainfall for the year:', avg data = \ [[ 0.75, 0.29619813, -0.29619813, -0.75 ], [ 0.29619813, 0.11697778, -0.11697778, -0.29619813], [-0.29619813, -0.11697778, 0.11697778, 0.29619813], [-0.75, -0.29619813, 0.29619813, 0.75 ]] outfile = open('tmp_table.dat', 'w') for row in data: for column in row: outfile.write('%14.8f' % column) outfile.write('\n') outfile.close() from math import log r = log(6) # call log function in math module import sys x = eval(sys.argv[1]) # access list argv in sys module from math import log as ln def present_amount(A0, p, n): return A0*(1 + p/(360.0*100))**n def initial_amount(A, p, n): return A*(1 + p/(360.0*100))**(-n) def days(A0, A, p): return ln(A/A0)/ln(1 + p/(360.0*100)) def annual_rate(A0, A, n): return 360*100*((A/A0)**(1.0/n) - 1) with open('interst.py', 'w') as outfile: outfile.write(""" from math import log as ln def present_amount(A0, p, n): return A0*(1 + p/(360.0*100))**n def initial_amount(A, p, n): return A*(1 + p/(360.0*100))**(-n) def days(A0, A, p): return ln(A/A0)/ln(1 + p/(360.0*100)) def annual_rate(A0, A, n): return 360*100*((A/A0)**(1.0/n) - 1) """) # How long time does it take to double an amount of money? from interest import days A0 = 1; A = 2; p = 5 n = days(A0, 2, p) years = n/365.0 print 'Money has doubled after %.1f years' % years if __name__ == '__main__': A = 2.2133983053266699 A0 = 2.0 p = 5 n = 730 print 'A=%g (%g) A0=%g (%.1f) n=%d (%d) p=%g (%.1f)' % \ (present_amount(A0, p, n), A, initial_amount(A, p, n), A0, days(A0, A, p), n, annual_rate(A0, A, n), p) def test_all_functions(): # Define compatible values A = 2.2133983053266699; A0 = 2.0; p = 5; n = 730 # Given three of these, compute the remaining one # and compare with the correct value (in parenthesis) A_computed = present_amount(A0, p, n) A0_computed = initial_amount(A, p, n) n_computed = days(A0, A, p) p_computed = annual_rate(A0, A, n) def float_eq(a, b, tolerance=1E-12): """Return True if a == b within the tolerance.""" return abs(a - b) < tolerance success = float_eq(A_computed, A) and \ float_eq(A0_computed, A0) and \ float_eq(p_computed, p) and \ float_eq(n_computed, n) assert success # could add message here if desired if __name__ == '__main__': test_all_functions() x = 20 r = eval('x + 1.1') r type(r) def f(x): return 2*x - 3 # one root x=1.5 eps = 1E-5 a, b = 0, 10 fa = f(a) if fa*f(b) > 0: print 'f(x) does not change sign in [%g,%g].' % (a, b) sys.exit(1) i = 0 # iteration counter while b-a > eps: i += 1 m = (a + b)/2.0 fm = f(m) if fa*fm <= 0: b = m # root is in left half of [a,b] else: a = m # root is in right half of [a,b] fa = fm x = m # this is the approximate root def bisection(f, a, b, eps): fa = f(a) if fa*f(b) > 0: return None, 0 # Alternative: raise ValueError( # 'No change of sign in [%g,%g]' % (a, b)) i = 0 # iteration counter while b-a > eps: i += 1 m = (a + b)/2.0 fm = f(m) if fa*fm <= 0: b = m # root is in left half of [a,b] else: a = m # root is in right half of [a,b] fa = fm return m, i print bisection(f=lambda x: 2*x-3, a=0, b=10, eps=1E-5) def test_bisection(): def f(x): return 2*x - 3 # only one root x=1.5 eps = 1E-5 x, iter = bisection(f, a=0, b=10, eps=eps) success = abs(x - 1.5) < eps # test within eps tolerance assert success, 'found x=%g != 1.5' % x if __name__ == '__main__': test_bisection()