Spyder is a nice development environment.
a=1.0 numbers=[0,1,2,3] for number in numbers: print number print a,type(a)
tup=1.0,2.0,3.0 print tupresults in
(1.0, 2.0, 3.0)and
tup=('Dirk Terrell','terrell@boulder.swri.edu','720-240-0147',5) print tupyields
('Dirk Terrell', 'terrell@boulder.swri.edu', '720-240-0147', 5)A special (and ugly) case is a tuple with one element:
tup=1, print tupyields
(1,)You can access the individual elements with [], e.g.
tup=1.0,2.0,3.0 print tup[0] print tup[1] print tup[2]yields
1.0 2.0 3.0You can also "slice" tuples to produce tuples containing subsets of the original tuple:
tup=('Dirk Terrell','terrell@boulder.swri.edu','720-240-0147',5) print tup[0:2] print tup[2:]yields
('Dirk Terrell', 'terrell@boulder.swri.edu') ('720-240-0147', 5)Some useful functions:
tup=1.0,2.0,3.0 print len(tup) print min(tup) print max(tup)yields
3 1.0 3.0Named tuples can be handy:
from collections import namedtuple Point=namedtuple('Point',['x','y','z']) p = Point(11, 22,33) print p print p.x,p.y,p.z
l=['Dirk Terrell', 'terrell@boulder.swri.edu', '720-240-0147', 5] print lyields
['Dirk Terrell', 'terrell@boulder.swri.edu', '720-240-0147', 5]You can also create an empty list and append items to it:
l=[] l.append('Dirk Terrell') l.append('terrell@boulder.swri.edu') l.append('720-240-0147') l.append(5) print lyields
['Dirk Terrell', 'terrell@boulder.swri.edu', '720-240-0147', 5]The + and * operators are handy. The + operator concatenates and the * operator repeats:
l1=['a','b','c'] l2=['d','e'] l=l1+l2 print l l=[0]*3 print lyields
['a', 'b', 'c', 'd', 'e'] [0, 0, 0]Since lists are mutable, we can change items:
l=['Dirk Terrell', 'terrell@boulder.swri.edu', '720-240-0147', 5] l[3]=4 print lyields
['Dirk Terrell', 'terrell@boulder.swri.edu', '720-240-0147', 4]We can remove items from a list
l=['a','b','c','d','e'] removed_item=l.pop(0) print "The item removed with pop was",removed_item print "l is now",l print del l[0] print "After del l[0] l is",l l.remove('e') print print "After l.remove('e') l is",l l=['a','b','c','d','e'] del l[2:5] print print "After del[2:5] l is",lyields
The item removed with pop was a l is now ['b', 'c', 'd', 'e'] After del l[0] l is ['c', 'd', 'e'] After l.remove('e') l is ['c', 'd'] After del[2:5] l is ['a', 'b']Iterating over a list:
asteroids=['Ceres','Juno','Vesta','Aquitania'] for asteroid in asteroids: print asteroidyields
Ceres Juno Vesta AquitaniaAccessing individual items and slicing is done as with tuples
print asteroids[0] print asteroids[1:3]yields
Ceres ['Juno', 'Vesta']Check if something is in a list:
if 'Algol' in asteroids: print 'Algol is an asteroid.' else: print 'Algol is not an asteroid.' if 'Ceres' in asteroids: print 'Ceres is an asteroid.' else: print 'Ceres is not an asteroid.'yields
Algol is not an asteroid. Ceres is an asteroid.If you need the indices as you iterate over a list, use the enumerate function:
asteroids=['Ceres','Juno','Vesta','Aquitania'] for i,asteroid in enumerate(asteroids): print i,asteroidyields
0 Ceres 1 Juno 2 Vesta 3 Aquitania
d={} d=dict()You can also create a dictionary with items:
asteroids={'1':'Ceres','3':'Juno','4':'Vesta','387':'Aquitania'}Assigments can be made directly:
asteroids={'1':'Ceres','3':'Juno','4':'Vesta','387':'Aquitania'} asteroids['2']='Pallas' print asteroids print asteroids['4']yields
{'1': 'Ceres', '3': 'Juno', '2': 'Pallas', '4': 'Vesta', '387': 'Aquitania'} VestaTesting if a key is in a dictionary:
asteroids={'1':'Ceres','3':'Juno','4':'Vesta','387':'Aquitania'} asteroids['2']='Pallas' for i in range(1001): astnum=str(i) if astnum in asteroids: print astnum,asteroids[astnum]yields
1 Ceres 2 Pallas 3 Juno 4 Vesta 387 AquitaniaValues can be any type, e.g. strings, tuples, lists, dictionaries
asteroids={'1':('Ceres',940),'3':('Juno',265),'4':('Vesta',510),'387':('Aquitania',100)} asteroids['2']=('Pallas',544) for i in range(1001): astnum=str(i) if astnum in asteroids: name,diameter=asteroids[astnum] print name,diameteryields
Ceres 940 Pallas 544 Juno 265 Vesta 510 Aquitania 100
python codefile.pyor in a Unix environment, set the code file executable (e.g., chmod 755 codefile.py) and the first line of the code pointing to the Python interpreter, e.g. codefile.py contains
#!/usr/bin/python a=1.0 print athen you can just type
codefile.py
numlist=range(1,11) print numlist print for i in numlist: print i,i*i print for i in numlist: print i,i*i-1yields
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 1 1 2 4 3 9 4 16 5 25 6 36 7 49 8 64 9 81 10 100 1 0 2 3 3 8 4 15 5 24 6 35 7 48 8 63 9 80 10 99
def square(x): return x*x numlist=range(1,11) print numlist for i in numlist: print i,square(i) print for i in numlist: print i,square(i)-1
def square(x): return x*x if __name__ == "__main__": numlist=range(1,11) print numlist for i in numlist: print i,square(i) print for i in numlist: print i,square(i)-1yields the same result as above. Here is a better example:
from math import atan def circle_area(radius): pi=atan(1.0)*4.0 return pi*radius*radius def circle_circumference(radius): pi=atan(1.0)*4.0 return 2.0*pi*radius if __name__ == "__main__": r=1.0 a=circle_area(r) d=circle_circumference(r) print a print dbut computing pi every function call is wasteful. How can we compute it once and make it available to all functions? Like so:
from math import atan def circle_area(radius): return pi*radius*radius def circle_circumference(radius): return 2.0*pi*radius if __name__ == "__main__": pi=atan(1.0)*4.0 r=1.0 a=circle_area(r) d=circle_circumference(r) print a print dWe might use these functions in other programs, so let's create a Python module. Create a file named circle.py with these lines:
from math import atan pi=atan(1.0)*4.0 def circle_area(radius): return pi*radius*radius def circle_circumference(radius): return 2.0*pi*radiusthen we can rewrite our program like this:
from circle import circle_area, circle_circumference if __name__ == "__main__": r=1.0 a=circle_area(r) d=circle_circumference(r) print a print dSince we have put the functions in a library of functions dealing with circles, the circle_ parts of the function names are redundant, so we can clean things up. The circle.py library should be
from math import atan pi=atan(1.0)*4.0 def area(radius): return pi*radius*radius def circumference(radius): return 2.0*pi*radiusand the main program (with slightly spiffier output) would be
#!/usr/bin/python from circle import area, circumference if __name__ == "__main__": r=1.0 a=area(r) d=circumference(r) print "For radius=1.0:" print " area is",a print " circumference is",dyielding
For radius=1.0: area is 3.14159265359 circumference is 6.28318530718
./plotfit.py cu_sge_v_obs.dat cu_sge_v_computed.datwe get the following list for sys.argv:
['./plotfit.py', 'cu_sge_v_obs.dat', 'cu_sge_v_computed.dat']Here is the plotfit.py program to read in two data files and plot them:
#!/usr/bin/python import sys import matplotlib.pyplot as plt if len(sys.argv)==3: obs_file_name=sys.argv[1] comp_file_name=sys.argv[2] else: print >> sys.stderr, 'You must enter the name of an observations file and a computed curve file.' exit() obs_file=open(obs_file_name,'r') obs_lines=obs_file.readlines() obs_file.close() comp_file=open(comp_file_name,'r') comp_lines=comp_file.readlines() comp_file.close() x_obs=[] y_obs=[] for line in obs_lines: if line[0]!="#": x,y=line.split() x_obs.append(float(x)) y_obs.append(float(y)) x_comp=[] y_comp=[] for line in comp_lines: if line[0]!="#": x,y=line.split() x_comp.append(float(x)) y_comp.append(float(y)) print len(obs_lines),'observations read in.' #fig=plt.figure(figsize=(15,12)) plt.plot(x_obs,y_obs,'ro',x_comp,y_comp,'k') plt.axis([-0.6,0.6,0.5,1.1]) plt.xlabel('Phase',fontsize=14,color='blue') plt.ylabel('Flux',fontsize=14,color='blue') plt.title('CU Sge V Data'+'\n'+r'$\sigma=0.02$',fontsize=18,color='green') plt.savefig('cusge.eps',dpi=600) plt.show()
class Star(): pass s0=Star() s0.temperature=3500 print "Star 0" print s0.temperatureyields
Star 0 3500But let's make it a little more useful:
class Star(): def __init__(self, t , r=0, m=0): self.temperature=t self.radius=r self.mass=m s1=Star(5000) print "Star 1" print s1.temperature,s1.radius,s1.mass print print "Star 2" s2=Star(7500,1.5,1.6) print s2.temperature,s2.radius,s2.mass s3=Star(m=2.0,r=1.7,t=8500) print print "Star 3" print s3.temperature,s3.radius,s3.massyields
Star 1 5000 0 0 Star 2 7500 1.5 1.6 Star 3 8500 1.7 2.0A subclassing example with iheritance and overloading:
class Top(): def name(self): print "Top class" def val(self): print "Top" class Sub(Top): def name(self): print "Sub class" s=Sub() s.name() s.val()yields
Sub class Top