Bo Zhang (NAOC, mailto:bozhang@nao.cas.cn) will have a few lessons on python.
python
to process astronomical data.These lectures are organized as below:
In [1]:
object
Out[1]:
In [2]:
dir()
Out[2]:
In [3]:
In
Out[3]:
In [4]:
a = 1.5
type(a)
Out[4]:
In [5]:
print isinstance(a, float)
print isinstance(a, object)
In [6]:
b = [1, 2, 3, 'abc']
type(b)
Out[6]:
In [7]:
b.append(4)
b
Out[7]:
In [8]:
c = (1, 2, 3, 'abc', 3)
type(c)
Out[8]:
In [9]:
c.count(3)
Out[9]:
In [10]:
c
Out[10]:
In [11]:
d = {'a': 123, 'b': 456}
d
Out[11]:
In [12]:
print d['a']
print d['b']
In [13]:
e = {1, 2}
print type(e)
e
Out[13]:
In [14]:
%%time
for i in range(10):
print i
In [15]:
%%time
for i in xrange(10):
print i
In [16]:
def f1yield(n):
n0 = 0
while n0 < n:
yield n-n0
n0 += 1
def f1print(n):
n0 = 0
while n0 < n:
print n-n0
n0 += 1
f = f1yield(5)
print type(f)
print f.next()
print f.next()
print f.next()
print f.next()
f = f1print(5)
print type(f)
In [17]:
def salesgirl(method):
def serve(*args):
print "Salesgirl:Hello, what do you want?", method.__name__
method(*args)
return serve
@salesgirl
def try_this_shirt(size):
if size < 35:
print "I: %d inches is to small to me" %(size)
else:
print "I:%d inches is just enough" %(size)
try_this_shirt(38)
In [18]:
print type(salesgirl)
print type(try_this_shirt)
In [19]:
def f2(x):
return 2*x
l2 = lambda x: 2*x
print f2(10)
print l2(10)
In [20]:
print type(f2)
print type(l2)
In [21]:
print f2
In [22]:
print l2
In [ ]:
In [23]:
class People():
"""here we define the People class
"""
name = ''
height = 180. # cm
weight = 140. # pound
energy = 100. # percent
energy_cost_per_work_hour = 10. # percent energy per work hour
energy_per_meal = 90. # percent energy per meal
def __init__(self, name='', height=180., weight=140., energy=100.):
self.name = name
self.height = height
self.weight = weight
self.energy = energy
def work(self, hours=1.):
if hours > 0. and hours < 10. and hours < self.energy/self.energy_cost_per_work_hour:
self.energy -= hours*self.energy_cost_per_work_hour
else:
if hours <= 0.:
raise ValueError('@Cham: hours must be positive!')
else:
raise ValueError('@Cham: energy ran out!')
def eat(self, num_meal=1.):
if num_meal > 0. and num_meal <= 5.:
self.energy += num_meal*self.energy_per_meal
if self.energy > 100.:
self.energy = 100.
else:
if num_meal <= 0.:
raise ValueError('@Cham: number of meals must be positive!')
else:
raise ValueError('@Cham: too many meals!')
def print_status(self):
print ''
print 'name: %s' % self.name
print 'height: %s' % self.height
print 'weight: %s' % self.weight
print 'energy: %s' % self.energy
print 'energy_cost_per_work_hour: %s' % self.energy_cost_per_work_hour
print 'energy_per_meal: %s' % self.energy_per_meal
jim = People('Jim')
jim.print_status()
jim.work(5)
jim.print_status()
jim.eat(2)
jim.print_status()
In [ ]: