<<

Python Introduction for Programmers

Edwin van der Helm

Python Scripts Python Introduction for Programmers Variables Math and Numbers Strings and Lists Indentation Logic Edwin van der Helm Functions Parameters Sterrewacht Leiden Advanced tricks Classes Januari 21, 2014 Packages Numpy Astropy PyRAF Pyplot Amuse Help Python Introduction for Programmers

Edwin van der Helm

Python

Scripts Variables Math and Numbers Strings and strw.leidenuniv.nl/∼vdhelm/teaching.php Lists Indentation Logic Functions Parameters Advanced tricks Classes

Packages Numpy Astropy PyRAF Pyplot Amuse Help Python Introduction for Programmers

Edwin van der Helm

Python

Scripts Variables Math and Numbers Strings and Lists Indentation Logic Functions Parameters Advanced tricks Classes

Packages Numpy Astropy PyRAF Pyplot Amuse Help Python Introduction Scripts for Programmers

Edwin van der Helm

Python 1 print"Hello World" Scripts Variables Math and Numbers Strings and Lists Indentation Logic $ python Functions >>> print"Hello World" Parameters Advanced tricks Hello World Classes

Packages $ python hello_world.py Numpy Hello World Astropy PyRAF Pyplot Amuse Help Python Introduction Variables for Programmers

Edwin van der Helm

Python 1 x = 2

Scripts 2 y = 2 + 2 Variables 3 z = x * 9 Math and Numbers 4 Strings and Lists 5 x = y = z = 0 Indentation Logic 6 Functions 7 x, y = 3, 4 Parameters Advanced tricks 8 y, x = x, y Classes 9

Packages 10 x = str (x) Numpy 11 Astropy PyRAF 12 print"y:", y Pyplot Amuse Help Python Introduction Math and Numbers for Programmers

Edwin van der Helm 1 print 2+3 #=5 2 print 2-3 #= -1 Python 3 print 10*3 #= 30 Scripts 4 print 12/3 #=4 Variables Math and 5 print 10%3 #=1 Numbers Strings and 6 print 10**3 #= 1000 Lists Indentation 7 Logic 8 print10+3*5 # first*,/ then +,- Functions Parameters 9 print (10 + 3) * 5 Advanced tricks 10 print -1**2 #= -(1**2) Classes 11 print 1/2 #=0 Packages 12 print 1./2. #= 0.5 Numpy Astropy 13 print 1.//2. #= 0.0 PyRAF Pyplot Amuse 1 from __future__ import division Help 2 print 1/2 Python Introduction Math and Numbers for Programmers

Edwin van der Helm 1 # Float 2 2.3 Python 3 -4. 1 # Explicit Scripts 4 .1 2 float (2) Variables Math and 5 2.99 e10 3 float (2**1000) Numbers Strings and 6 4 Lists -1e1 , -1E1 int (2.3) Indentation 7 5 int ( -2.3) Logic 8 # Long 6 int (2**1000) Functions Parameters 9 2**1000 7 long (2) Advanced tricks 10 2L, 2l 8 str (2) Classes 11 9 complex (1 ,2) Packages 12 10 Numpy # Complex Astropy 13 1J 11 # Test PyRAF Pyplot 14 2. + 3j 12 type ((2 -3j)) Amuse 15 (2.+3j).real Help 16 (2+3j).imag Python Introduction Strings and Lists for Programmers

Edwin van der Helm

Python Scripts 1 x =’test string’ Variables Math and 2 Numbers Strings and 3 ’doesn\’t’ Lists Indentation 4 "doesn’t" Logic 5 ’"Yes," he said.’ Functions 6 Parameters Advanced tricks 7 """ This isa multi Classes 8 line string with Packages 9 an entire story in it.""" Numpy Astropy PyRAF Pyplot Amuse Help Python Introduction Strings and Lists for Programmers 1 s ="I havea telescope!" Edwin van der Helm 2 len (s) 3 ’tel’+"escope" # Concatination Python 4 ’telescope’ + 100 # won’t work Scripts 5 ’telescope’+ str (100) Variables Math and 6 ’telescope’ * 100 # Be careful Numbers Strings and 7 ’telescope’*’100’ Lists Indentation 8 Logic 9 s [0] # First character Functions 10 Parameters s [1] # Second character Advanced tricks 11 s [2:10] # Substring Classes 12 s [100] # Error Packages 13 s[ -1] # Last character Numpy Astropy 14 PyRAF Pyplot 15 s = s.strip() Amuse 16 s1 = s.split() Help 17 s2 = s.split(’e’) 18 s = s.replace("telescope","computer") 19 "Name: {0}, age: {1}". format (’John’, 35) Python Introduction Strings and Lists for Programmers

Edwin van der Helm 1 x = ["I","havea","telescope!", 4] Python 2 Scripts 3 # Slices Variables Math and 4 x [0] Numbers Strings and 5 x [1:] Lists Indentation 6 x [::2] Logic 7 x [2] ="computer!" Functions 8 Parameters x [1:3] =’bla’ Advanced tricks 9 Classes 10 # Dictionary Packages 11 y = {1323:’Bob’, 6543:’Alice’} Numpy Astropy 12 print y[1323] PyRAF Pyplot 13 y = {’Bob’:1323,’Alice’:6543} Amuse 14 printy[’Alice’] Help Python Introduction Strings and Lists for Programmers

Edwin van der Helm

Python

Scripts Variables Math and Numbers Strings and 1 # List comprehensions Lists Indentation 2 print range (10) Logic 3 squares = [i**2 fori in range (30)] Functions 4 Parameters dict_squares = [i:i**2 fori in range (30)] Advanced tricks Classes

Packages Numpy Astropy PyRAF Pyplot Amuse Help Python Introduction Strings and Lists for Programmers

Edwin van der Helm

Python 1 x = ["I","havea","telescope!", 4]

Scripts 2 Variables 3 "".join(x[:-1]) Math and Numbers 4 x. append ("yes") Strings and Lists 5 x. extend ( range (6)) Indentation Logic 6 x.insert(2,"good") Functions 7 x. remove (’I’) Parameters Advanced tricks 8 x. pop () Classes 9 x. index (’havea’) Packages 10 x. count (4) Numpy 11 x. sort () Astropy PyRAF 12 x.reverse() Pyplot Amuse Help Python Introduction Indentation for Programmers

Edwin van der Helm 1 fori in range (3, 20, 2): Python 2 print"This is part of the loop", i Scripts Variables 3 print"This is also part of the loop" Math and Numbers 4 print"This is not part of the loop" Strings and Lists 5 Indentation 6 Logic # Use4 spaces or one tab as indentation. Functions 7 # Please be consistent with your indentation Parameters 8 Advanced tricks 9 fori in range (5): Classes 10 forj in range (5): Packages Numpy 11 print"Inner loop", i, j Astropy 12 PyRAF print"Outer loop", i, j Pyplot 13 print"Not in the loop" Amuse Help Python Introduction Indentation for Programmers

Edwin van der Helm 1 for letter in’Python’: 2 if letter ==’h’: Python 3 break Scripts 4 print’Current Letter:’, letter Variables Math and 5 Numbers Strings and 6 for letter in’Python’: Lists Indentation 7 if letter ==’h’: Logic 8 continue Functions Parameters 9 print’Current Letter:’, letter Advanced tricks 10 Classes 11 for letter in’Python’: Packages 12 if letter ==’x’: Numpy Astropy 13 break PyRAF Pyplot 14 print’Current Letter:’, letter Amuse 15 else: Help 16 print’Nox in python’ Python Introduction Logic for Programmers

Edwin van der Helm 1 if’Steven’ in[’Bob’,’Steven’,’Fred’]: 2 print’Here!’ Python 3 Scripts 4 if’Carol’ not in[’Bob’,’Steven’,’Fred’]: Variables Math and 5 print’Away!’ Numbers Strings and 6 Lists Indentation 7 test = a == b Logic 8 if test: print’Equal’ Functions Parameters 9 Advanced tricks 10 x = int ( raw_input ("Enter integer:")) Classes 11 if x == 0: Packages 12 print’Zero’ Numpy Astropy 13 elif x == 1: PyRAF Pyplot 14 print’One’ Amuse 15 else: Help 16 print’Not binary’ Python Introduction Logic for Programmers

Edwin van der Helm 1 "sub" in"mysubstring" Python 2 "mystring".startswith("myst") Scripts Variables 3 Math and Numbers 4 0 and"not empty" Strings and Lists 5 False or"" or [1,2,3] or 42 Indentation 6 Logic "string" is not None Functions 7 Parameters 8 2 < x <= 10 Advanced tricks 9 Classes 10 x = y = [1,2,3] Packages Numpy 11 [1 ,2 ,3] == x Astropy 12 PyRAF [1 ,2 ,3] isx Pyplot 13 y isx Amuse Help Python Introduction Functions for Programmers

Edwin van der 1 def my_function(x, y): Helm 2 a = x + y Python 3 printa

Scripts 4 Variables 5 z = 10 Math and Numbers 6 my_function(z, 2) Strings and Lists 7 my_function(z, z-2) Indentation Logic 8 Functions 9 # Return values Parameters Advanced tricks 10 def my_function_2(x, y): Classes 11 a = x + y Packages 12 b = x * y Numpy 13 return a,b Astropy PyRAF 14 Pyplot Amuse 15 if __name__ =="__main__": Help 16 print my_function_2(1, 2) 17 m, p = my_function_2(1, 2) Python Introduction Parameters for Programmers

Edwin van der Helm 1 def my_function(x, y):

Python 2 print x+y**2 3 Scripts Variables 4 if __name__ =="__main__": Math and Numbers 5 # Calling by keyword Strings and Lists 6 my_function(y=2, x=3) Indentation Logic 7 Functions 8 # default values Parameters Advanced tricks 9 def my_function_2(x=1, y=1): Classes 10 print x + y**2

Packages 11 Numpy 12 if __name__ =="__main__": Astropy PyRAF 13 my_function_2(2, 3) Pyplot Amuse 14 my_function_2(y=2) Help 15 my_function_2() Python Introduction Parameters for Programmers 1 def my_function(x, y): Edwin van der Helm 2 print x+y**2 3 Python 4 if __name__ =="__main__": Scripts 5 arguments = [2, 3] Variables Math and 6 my_function(*arguments) Numbers Strings and 7 Lists Indentation 8 params = {’y’:3,’x’:5} Logic 9 my_function(**params) Functions 10 Parameters Advanced tricks 11 def my_function_2(*args, **kwargs): Classes 12 for arg in args: Packages 13 print arg Numpy Astropy 14 PyRAF Pyplot 15 for name, value in kwargs.items(): Amuse 16 print name,"has value", value Help 17 18 if __name__ =="__main__": 19 my_function_2(1, 2, 3, x=4, y=5, z=6) Python Introduction Advanced tricks for Programmers 1 def todo_function(x): Edwin van der Helm 2 pass 3 Python 4 def change_and_call(x, y, Scripts 5 func=todo_function) Variables Math and 6 a = x % y Numbers Strings and 7 func (a) Lists Indentation 8 Logic 9 def other_function(x): Functions 10 Parameters def inner_function(x) Advanced tricks 11 printx Classes 12 Packages 13 change_and_call(x, x+1, inner_function) Numpy Astropy 14 PyRAF Pyplot 15 if __name__ =="__main__": Amuse 16 change_and_call(1, 2, other_function) Help 17 18 print change_and_call(1, 2, 19 lambda y: y**2) Python Introduction Classes for Programmers

Edwin van der Helm 1 class Planet( object ): Python 2 def __init__(self , name, mass): Scripts 3 self . mass = mass Variables Math and 4 self . name = name Numbers Strings and 5 Lists Indentation 6 def display_planet( self ): Logic 7 s ="Name:{p.name} mass:{p.mass}" Functions 8 Parameters print s. format (p= self ) Advanced tricks 9 Classes 10 if __name__ =="__main__": Packages 11 planet1 = Planet("Earth", 5.972e24) Numpy Astropy 12 planet2 = Planet("Venus", 4.867e24) PyRAF Pyplot 13 planet1.display_planet() Amuse 14 planet2.display_planet() Help Python Introduction Classes for Programmers 1 Edwin van der class Gas_Giant(Planet): Helm 2 def display_planet( self ): 3 s="{p.name}, Gas giant,M={p.mass}" Python 4 print s. format (p= self ) Scripts Variables 5 Math and Numbers 6 def orig_display( self ): Strings and Lists 7 Planet.display_planet( self ) Indentation 8 Logic Functions 9 if __name__ =="__main__": Parameters 10 planet3 = Gas_Giant("Jupiter", 1.9e+27) Advanced tricks 11 planet3.display_planet() Classes 12 planet3.orig_display() Packages Numpy 13 Astropy 14 PyRAF planet3.radius = 7.15e+07 Pyplot 15 print hasattr ( planet1 ,"radius") Amuse 16 Help 17 planet3.show = planet3.display_planet 18 planet3.show() Python Introduction Packages for Programmers

Edwin van der Helm

Python 1 Scripts import numpy Variables 2 Math and Numbers 3 from matplotlib import pyplot Strings and Lists 4 import matplotlib.pyplot as plt Indentation Logic 5 from matplotlib import pyplot, gridspec Functions 6 Parameters Advanced tricks 7 from astropy.io import Classes 8

Packages 9 # Please don’t use: Numpy 10 from amuse.lab import* Astropy PyRAF Pyplot Amuse Help Python Introduction Numpy for Programmers

Edwin van der Helm

Python Scripts 1 import numpy Variables Math and 2 Numbers Strings and 3 a = numpy.array([1,3,5,7,9]) Lists Indentation 4 b = numpy.array([3,5,6,7,9]) Logic 5 Functions 6 Parameters printa+b Advanced tricks 7 printa*b Classes 8 print2*a Packages 9 print a**2 Numpy Astropy PyRAF Pyplot Amuse Help Python Introduction Numpy for Programmers

Edwin van der 1 import numpy Helm 2 Python 3 a = [[i + 10* j fori in range (10)]

Scripts 4 forj in range (11)] Variables 5 a = numpy.array(a) Math and Numbers 6 printa Strings and Lists 7 print a.shape Indentation Logic 8 Functions 9 # Slices Parameters Advanced tricks 10 print a[3,4] Classes 11 print a[:,5] Packages 12 print a[2:-3,:3] Numpy 13 print a[2:-3,:9:2] Astropy PyRAF 14 Pyplot Amuse 15 print22

Edwin van der Helm 1 print a.astype( float ) Python 2 b = a. copy () Scripts 3 printa isb Variables Math and 4 Numbers Strings and 5 print a. sum () Lists Indentation 6 print a.mean() Logic 7 print a.std() Functions 8 Parameters print a. max () Advanced tricks 9 print a. min () Classes 10 Packages 11 test = (20 < a) & (a < 40) Numpy Astropy 12 print test. all () PyRAF Pyplot 13 print test. any () Amuse 14 print test. sum () Help Python Introduction Numpy for Programmers

Edwin van der Helm 1 b = a **2 Python 2 = a.transpose() Scripts 3 printc Variables Math and 4 print c.dot(b) Numbers Strings and 5 print numpy.cross(a[:2,1], a[-2:,2]) Lists Indentation 6 print numpy.cross([1, 2, 3], [0, 1]) Logic 7 Functions 8 Parameters ma = numpy.asmatrix(a) Advanced tricks 9 mb = numpy.asmatrix(b[:5,:5]) Classes 10 mc = numpy.asmatrix(c) Packages 11 print ma * mc Numpy Astropy 12 print mb**2 PyRAF Pyplot 13 print mb.T Amuse 14 print mb.I Help Python Introduction Numpy for Programmers

Edwin van der Helm

Python $ cat planets.txt

Scripts # Name, mass(kg), radius(m) Variables Mercury 3.3e+23 2.44e+06 Math and Numbers Venus 4.87e+24 6.05e+06 Strings and Lists Earth 5.97e+24 6.38e+06 Indentation Logic Mars 6.42e+23 3.4e+06 Functions Parameters Advanced tricks 1 import numpy as np Classes 2 mass, radius = np.loadtxt("planets.txt", Packages 3 dtype =float , Numpy Astropy 4 usecols=(1,2), PyRAF Pyplot 5 unpack =True) Amuse Help Python Introduction Astropy for Programmers

Edwin van der Helm 1 from astropy.io import fits Python 2 Scripts Variables 3 # open() has many keyword options. Math and Numbers 4 fits_file = fits. open (’input.fits’) Strings and Lists 5 print fits_file.info() Indentation 6 Logic Functions 7 print fits_file[0].header() Parameters 8 Advanced tricks 9 # The data can be read asa numpy array Classes 10 data = fits_file[0].data Packages Numpy 11 print data.shape Astropy 12 PyRAF print data.mean() Pyplot 13 print data[10:-10, 10:-10] Amuse Help Python Introduction Astropy for Programmers

Edwin van der Helm

Python

Scripts It also includes: Variables Math and Units and coordinates Numbers I Strings and Lists I Fitting Indentation Logic I Convolution and filtering Functions Parameters I Cosmology Advanced tricks Classes I Astrostatistics tools

Packages I ... Numpy Astropy PyRAF Pyplot Amuse Help Python Introduction PyRAF for Programmers

Edwin van der 1 import os Helm 2 from pyraf import Python 3

Scripts 4 for img in os.listdir("fits_files/"): Variables 5 iraf.imstat(img) Math and Numbers 6 newimg = img.replace(’sci’,’sig’) Strings and Lists 7 iraf.imcalc(img, newimg,’sqrt(img)’) Indentation Logic 8 Functions 9 iraf.imstat.nclip = 3 Parameters Advanced tricks 10 iraf.imstat.lsigma = 5 Classes 11 iraf.imstat.usigma = 5 Packages 12 Numpy 13 # now imstat uses sigma clipping Astropy PyRAF 14 iraf.imstat(im1) Pyplot Amuse 15 Help 16 # revert defaults using unlearn 17 iraf.unlearn(’imstat’) Python Introduction Pyplot for Programmers 1 import numpy Edwin van der 2 from matplotlib import pyplot Helm 3

Python 4 x = numpy.linspace(0, 10, 100)

Scripts 5 y = numpy.cos(x)**2 Variables 6 Math and Numbers 7 pyplot.plot(x, y) Strings and Lists 8 pyplot.show() Indentation Logic Functions Parameters 1.0 Advanced tricks

Classes 0.8 Packages Numpy 0.6 Astropy PyRAF Pyplot Amuse 0.4 Help 0.2

0.0 0 2 4 6 8 10 Python Introduction Pyplot for Programmers 1 x = numpy.linspace(0, 10, 100) Edwin van der 2 m = numpy.cos(x) Helm 3 d = m + numpy.random.normal(scale=0.1, Python 4 size =100)

Scripts 5 pyplot.plot(x, m) Variables 6 pyplot.scatter(x, d) Math and Numbers 7 pyplot.savefig("model.pdf") Strings and Lists Indentation Logic Functions 1.5 Parameters Advanced tricks 1.0 Classes 0.5 Packages Numpy 0.0 Astropy PyRAF Pyplot 0.5 Amuse

Help 1.0

1.5 2 0 2 4 6 8 10 12 Python Introduction Pyplot for Programmers 1 figure = pyplot.figure(figsize = (10, 7)) Edwin van der 2 Helm 3 pyplot.plot(x, model, label="model")

Python 4 pyplot.scatter(x, data, label="data")

Scripts 5 Variables 6 pyplot.xlim([0, 10]) Math and Numbers 7 pyplot.ylim([-2, 2]) Strings and Lists 8 pyplot.xlabel("time") Indentation Logic 9 pyplot.ylabel("measurement") Functions 10 pyplot.title("plot with options") Parameters Advanced tricks 11 pyplot.legend(loc="upper right", ncol=2, Classes 12 fancybox =True, shadow=True)

Packages

Numpy plot with options 2.0 Astropy model data 1.5 PyRAF Pyplot 1.0 Amuse 0.5

0.0 Help measurement 0.5

1.0

1.5

2.0 0 2 4 6 8 10 time Python Introduction Pyplot for Programmers 1 X = numpy.linspace(-5, 5, 200) Edwin van der 2 Y = numpy.linspace(-5, 5, 200) Helm 3 X, Y = numpy.meshgrid(X, Y) Python 4 Z = (numpy.sin(X**2 + Y**2)

Scripts 5 * numpy.cos(X + Y**2) Variables 6 * numpy.sin(Y)) Math and Numbers 7 Strings and Lists 8 Indentation pyplot.contour(X, Y, Z) Logic 9 pyplot.savefig("contour.pdf") Functions Parameters Advanced tricks

Classes 4 Packages Numpy 2 Astropy

PyRAF 0 Pyplot Amuse 2 Help

4

4 2 0 2 4 Python Introduction Pyplot for Programmers 1 x = numpy.linspace(0, 10, 100) Edwin van der 2 y = numpy.cos(x)**2 Helm 3 y2 = numpy.sin(x)**2 Python 4

Scripts 5 figure = pyplot.figure(figsize = (10, 6)) Variables 6 subplot = figure.add_subplot(211) Math and Numbers 7 pyplot.plot(x, y) Strings and Lists 8 Indentation subplot = figure.add_subplot(212) Logic 9 pyplot.plot(x, y2) Functions Parameters Advanced tricks 1.0

Classes 0.8

Packages 0.6 0.4 Numpy 0.2 Astropy 0.0 PyRAF 0 2 4 6 8 10 Pyplot 1.0

Amuse 0.8 Help 0.6 0.4

0.2

0.0 0 2 4 6 8 10 Python Introduction Pyplot for Programmers 1 from matplotlib import pyplot, gridspec Edwin van der 2 gs = gridspec.GridSpec(2, 3, Helm 3 width_ratios=[3,2,2])

Python 4 pyplot.subplot(gs[:, 0])

Scripts 5 pyplot.plot(x,y) Variables 6 pyplot.subplot(gs[0, 1:]) Math and Numbers 7 pyplot.plot(x,y) Strings and Lists 8 pyplot.subplot(gs[1, 1]) Indentation Logic 9 pyplot.plot(x,y) Functions 10 pyplot.subplot(gs[1, 2]) Parameters Advanced tricks 11 pyplot.plot(x,y) Classes 1.0 1.0 Packages 0.8 0.6 Numpy 0.8 Astropy 0.4 PyRAF 0.2 0.6 Pyplot 0.0 0 2 4 6 8 10 Amuse 1.0 1.0 0.4 Help 0.8 0.8 0.6 0.6

0.2 0.4 0.4

0.2 0.2

0.0 0.0 0.0 0 2 4 6 8 10 0 2 4 6 8 10 0 2 4 6 8 10 Python Introduction Amuse for Programmers

Edwin van der Helm 1 from amuse.lab import*

Python 2 3 Scripts number_of_stars = 100 Variables 4 size = 2 | units.pc Math and Numbers 5 Strings and Lists 6 masses = new_salpeter_mass_distribution( Indentation Logic 7 number_of_stars, mass_min=2|units.MSun) Functions 8 Parameters Advanced tricks 9 converter = nbody_system.nbody_to_si( Classes 10 masses . sum (), size )

Packages 11 stars = new_plummer_model( Numpy 12 number_of_stars, Astropy PyRAF 13 convert_nbody=converter) Pyplot Amuse 14 Help 15 stars.mass = masses Python Introduction Amuse for Programmers

Edwin van der Helm

Python 1 Scripts gravity = Hermite(converter) Variables 2 stellar = SeBa() Math and Numbers 3 Strings and Lists 4 gravity.particles.add_particles(stars) Indentation Logic 5 stellar.particles.add_particles(stars) Functions 6 Parameters Advanced tricks 7 interaction = (stellar.particles. Classes 8 new_channel_to(

Packages 9 gravity.particles, Numpy 10 attributes=["mass","radius"])) Astropy PyRAF Pyplot Amuse Help Python Introduction Amuse for Programmers

Edwin van der Helm

Python Scripts 1 time = 0 | units.Myr Variables Math and 2 while time <= end_time: Numbers Strings and 3 interaction.copy() Lists Indentation 4 Logic 5 time += timestep Functions 6 Parameters gravity.evolve_model(time) Advanced tricks 7 stellar.evolve_model(time) Classes 8 Packages 9 plot_or_save(gravity, stellar, time) Numpy Astropy PyRAF Pyplot Amuse Help Python Introduction Help for Programmers

Edwin van der Helm I http://www.strw.leidenuniv.nl/python

Python I google Scripts Variables Math and 1 import numpy Numbers Strings and 2 print numpy Lists Indentation 3 print dir ( numpy ) Logic 4 print [s fors in dir ( numpy ) if"min" in s] Functions Parameters Advanced tricks >>> import numpy Classes >>> help(numpy) Packages Numpy >>> help(numpy.linspace) Astropy PyRAF Pyplot Amuse $ python -m pdb my_program.py Help