Welcome to my lessons


Bo Zhang (NAOC, mailto:bozhang@nao.cas.cn) will have a few lessons on python.

  • These are very useful knowledge, skills and code styles when you use python to process astronomical data.
  • All materials can be found on my github page.
  • jupyter notebook (formerly named ipython notebook) is recommeded to use

These lectures are organized as below:

  1. install python
  2. basic syntax
  3. numerical computing
  4. scientific computing
  5. plotting
  6. astronomical data processing
  7. high performance computing
  8. version control

object


In [1]:
object


Out[1]:
object

In [2]:
dir()


Out[2]:
['In',
 'Out',
 '_',
 '_1',
 '__',
 '___',
 '__builtin__',
 '__builtins__',
 '__doc__',
 '__name__',
 '_dh',
 '_i',
 '_i1',
 '_i2',
 '_ih',
 '_ii',
 '_iii',
 '_oh',
 '_sh',
 'exit',
 'get_ipython',
 'quit']

In [3]:
In


Out[3]:
['', u'object', u'dir()', u'In']

In [4]:
a = 1.5
type(a)


Out[4]:
float

In [5]:
print isinstance(a, float)
print isinstance(a, object)


True
True

Lists and Tuples


In [6]:
b = [1, 2, 3, 'abc']
type(b)


Out[6]:
list

In [7]:
b.append(4)
b


Out[7]:
[1, 2, 3, 'abc', 4]

In [8]:
c = (1, 2, 3, 'abc', 3)
type(c)


Out[8]:
tuple

In [9]:
c.count(3)


Out[9]:
2

In [10]:
c


Out[10]:
(1, 2, 3, 'abc', 3)

Dictionaries and Sets


In [11]:
d = {'a': 123, 'b': 456}
d


Out[11]:
{'a': 123, 'b': 456}

In [12]:
print d['a']
print d['b']


123
456

In [13]:
e = {1, 2}
print type(e)
e


<type 'set'>
Out[13]:
{1, 2}

Iterators and Generators


In [14]:
%%time
for i in range(10):
    print i


0
1
2
3
4
5
6
7
8
9
CPU times: user 0 ns, sys: 0 ns, total: 0 ns
Wall time: 220 µs

In [15]:
%%time
for i in xrange(10):
    print i


0
1
2
3
4
5
6
7
8
9
CPU times: user 0 ns, sys: 0 ns, total: 0 ns
Wall time: 249 µs
  • mutable immutable
  • iterable

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)


<type 'generator'>
5
4
3
2
5
4
3
2
1
<type 'NoneType'>

Decorators


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)


Salesgirl:Hello, what do you want? try_this_shirt
I:38 inches is just enough

In [18]:
print type(salesgirl)
print type(try_this_shirt)


<type 'function'>
<type 'function'>

lambda


In [19]:
def f2(x):
    return 2*x

l2 = lambda x: 2*x

print f2(10)
print l2(10)


20
20

In [20]:
print type(f2)
print type(l2)


<type 'function'>
<type 'function'>

In [21]:
print f2


<function f2 at 0x7f0b94286230>

In [22]:
print l2


<function <lambda> at 0x7f0b94286398>

In [ ]:

class

you should understand the difference between "class" and "instance"


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()


name:                      Jim
height:                    180.0
weight:                    140.0
energy:                    100.0
energy_cost_per_work_hour: 10.0
energy_per_meal:           90.0

name:                      Jim
height:                    180.0
weight:                    140.0
energy:                    50.0
energy_cost_per_work_hour: 10.0
energy_per_meal:           90.0

name:                      Jim
height:                    180.0
weight:                    140.0
energy:                    100.0
energy_cost_per_work_hour: 10.0
energy_per_meal:           90.0

HOMEWORK

  1. use generator to generate the Fibonacci sequence
  2. try to define a simple class

In [ ]: