Документ взят из кэша поисковой машины. Адрес оригинального документа : http://www.arcetri.astro.it/~lfini/IntroduzioneAPython.pdf
Дата изменения: Wed Jun 13 19:59:06 2012
Дата индексирования: Tue Oct 2 03:38:45 2012
Кодировка:

Поисковые слова: redshift survey


Versioni


2.4.6, 2.5.6, 2.6.8, 2.7.2 3.0.1, 3.1.4, 3.2.2





Piattaforme


Linux (preinstallato) Windows
­ ­



www.python.org Active State



Mac Android ....
L.Fini - Introduzione al linguaggio Python








Linguaggio scripting


... ma non solo Procedurale Ad oggetti Funzionale (... un po')



Supporta stili diversi




Semi-interpretato Tipizzato "a modo suo"




Oggetti tipizzati Variabili non tipizzate



Gestione memoria automatica Vasta libreria standard
L.Fini - Introduzione al linguaggio Python






Tipi numerici


int, long, float, complex
a=3 b=3.1415926 c=15000L d=a+b e=7/2 f=float(333) g=complex(1.5,2) h=None i=True print f * g print e

L.Fini - Introduzione al linguaggio Python




Operazioni
x-y x/y x%y

x+y x*y x // y abs(x) int(x) long(x) float(x) complex(re,im) c.conjugate() divmod(x, y) pow(x, y)

x ** y

L.Fini - Introduzione al linguaggio Python




Operazioni su bit

x|y x^y x&y x << n x >> n ~x

L.Fini - Introduzione al linguaggio Python




Stringhe e semplici operazioni

a='Sopra la panca la capra campa' b="Trentatre' "+"trentini" print a print b print a+7 a[3] a[3:7] a[:7] a[-1] a='%d + %d vale %d'%(3,2,5) a[3]='t'
L.Fini - Introduzione al linguaggio Python

print 7+a




Sequenze
string list tuple

a='Sopra la' b=['a',3,5,3.14] c=(3,'x',0,'I')


Operazioni

3 in b 'h' not in a b+b a * 3, 4 * c a[4] b[1:3] c[0:3:2] len(a) min(b) max(b)
L.Fini - Introduzione al linguaggio Python




Slices

a=[12,14,22,27,31,44] 0 -6 a: 0 -6 a[3] a[-2] a[3:7] a[-3:-1] a[-3:] a[:3]
L.Fini - Introduzione al linguaggio Python

12 -5 -4

3 -3

4 -2

5 -1

12 14 22 27 31 44 12 -5 -4 3 -3 4 -2 5 -1 6




Operazioni su list -1
s[i] = x s[i:j] = [t] del s[i:j] s[i:j:k] = [t] s.append(x) s.extend(x) s.count(x) s.insert(i, x) s.pop( ) s.reverse() s.sort([cmp[,key[,reverse]]]) i s[i:j]=[]

L.Fini - Introduzione al linguaggio Python




Operazioni su list -2
map(int,s) filter(int,s) reduce(lambda x,y: x+y,s)



List comprehension

[x*x for x in range(0,10)] [0 for x in range(0,10)] [(x,x*x) for x in range(0,10)] frutta = [' mela', ' pera '] [x.strip() for x in frutta]

L.Fini - Introduzione al linguaggio Python




set / frozenset
s=set(('uno','tre',44,3.14)) p=set(('no',44,'due')) >>> s >>> 44 in s >>> len(s) >>> s.union(p) >>> s.intersection(p) >>> s.add('abc') >>> s.update(p)

L.Fini - Introduzione al linguaggio Python




dict

(array associativi)

d = {'a':'a','b':3,'c':1.44} len(d) d['b'] del d['a'] 'a' in d d.has_key('c') d.items() d.keys() n=dict(c=125.7,pi=3.14) d.update(n) 'b' not in d d.get('c'[, default]) d['b'] = 3.5

L.Fini - Introduzione al linguaggio Python




file
f = open("pippo.xxx"[,'r']) f.close() f.readline() f.read([size]) f.seek(n[,whence]) f.tell() f.write(str) f.flush() f.name
Vedi frasi di controllo

# 0,1,2

f=open("hello.txt") for line in f: print line

L.Fini - Introduzione al linguaggio Python




Espressioni particolarmente pythoniche

a = x if b>3 else y x,y = y,x



Espressioni lambda

>>> a = lambda x,y: x+y >>> a(1,3)

L.Fini - Introduzione al linguaggio Python




Copia e riferimento a oggetti

>>> >>> >>> >>> >>> >>> >>> >>> >>> >>>

a = [1,2,3,4] b=a b a[2]=77 b b=a[:] c=list(a) a[2]=3 b c

Copia "shallow" vs. "deep"
L.Fini - Introduzione al linguaggio Python




Frasi di controllo
if a>b: a=b elif b>a: b=a else: b=a=0
blocchi indentati

while a
for k in range(10): sum += k*k break continue
L.Fini - Introduzione al linguaggio Python




Es. lettura file
Tradizionale f=open("hello.txt") while True: line=f.readline() if not line: break print line

Pythonico moderno f=open("hello.txt") for line in f: print line

L.Fini - Introduzione al linguaggio Python




Funzioni

(file: func1.py)

def func(a,b,default=7): if a>b: return a elif a
L.Fini - Introduzione al linguaggio Python




Procedure

(file: func2.py)

def func(a,b,default=7): if a>b: print a elif a
L.Fini - Introduzione al linguaggio Python




Argomenti

(file: func3.py)

def func(a,*p,**kw): print 'arg1:',a print 'posiz:',p print 'keyw:',kw >>> execfile('func3.py') >>> func(1,2,3,4,pippo=5,pluto=6) >>> func()

L.Fini - Introduzione al linguaggio Python




Funzioni built-in -1

abs(x) all((0,1,2,3)) any((0,1,2,3)) bin(10) chr(55) cmp(2,3) divmod(7,5) hex(121) int('12',16) max((1,2,3)) pow(2,0.5) oct(11) long('32',5) min((1,2,3)) unichr(55) ord('7')

L.Fini - Introduzione al linguaggio Python




Funzioni built-in -2
Python 2.6 3.0

print(...)

sorted((8,7,6,5,4,3.14,1)) range(0,30,5) xrange(0,30,5)

raw_input('Prompt ') round(1.4142135623730951,2) zip([1,2,3],[4,5,6]) exec('a=3') execfile('a.py')

L.Fini - Introduzione al linguaggio Python




Classi

-1

class Empty: pass - class1.py class Selector: t=('uno','due','tre') def __init__(self,n): self.sel=Selector.t[n] def value(self): return self.sel a=Selector(1) b=Selector(2) print a.value() print b.value()

L.Fini - Introduzione al linguaggio Python




Classi


-2

NO overload NO private/protected (*) SI: ereditarieta'





- class2.py class NewSelector(Selector): def __init__(self,n): Selector.__init__(self,n-1) def printit(self): print self.sel a=NewSelector(1) print a.value() a.printit() (*) Ma: __var
L.Fini - Introduzione al linguaggio Python




Classi

-3
- class3.py

class xlist(list): def __init__(self,*k): list.__init__(self) self.sum=0 self.sumsq=0 if k: self.extend(k) def append(self,value): self.sum += value self.sumsq += value*value list.append(self,value) def extend(self,values): list.extend(self,values) self.sum=sum(values) self.sumsq=reduce(lambda x,y: \ x+y*y, values, self.sumsq) if __name__ == '__main__': a=xlist(1,2,3) print a,'\n',a.sum,'\n',a.sumsq

>>> from class3 import * >>> a=xlist(1,2,3)
L.Fini - Introduzione al linguaggio Python




Errori ed Eccezioni

while true print "Vero!"

- except1.py
while True: try: x = int(raw_input('Numero ')) break except ValueError: print "Non valido. Riprova"

e=Exception('Errore tutto mio') raise e else: finally:

L.Fini - Introduzione al linguaggio Python




Moduli
- fibo.py

_MAXFIBO=1000 def fib(n): # Scrivi ser.Fib. if n>_MAXFIBO: return a, b = 0, 1 while b < n: print b, a, b = b, a+b def fib2(n): # return ser.Fib if n>_MAXFIBO: return [] result = [] a, b = 0, 1 while b < n: result.append(b) a, b = b, a+b nota: return result _MAXFIBO >>> >>> >>> >>> import fibo dir(fibo) fibo.fib(7) fibo.fib2(11)

>>> from fibo import * >>> from fibo import fib >>> import fibo as fb
L.Fini - Introduzione al linguaggio Python




Namespace

-1

>>> dir() ['__builtins__', '__doc__', '__name__', '__package__'] >>> a=5.4 >>> def p3(v): ... return v+3 >>> dir() ['__builtins__', '__doc__', '__name__', '__package__', 'a', 'p3']

__name__

a p3

sono elementi del namespace global

... provare anche:
>>> type(a) >>> type(p3)
L.Fini - Introduzione al linguaggio Python




Namespace

-2

>>> import class4 as xl >>> dir() ['__builtins__', '__doc__', '__name__', '__package__', 'a', 'p3', 'xl'] xl Х un elemento del namespace global

>>> dir(xl) ... >>> dir(xl.xlist)

xlist Х un elemento del namespace xl

... esaminare anche:
>>> >>> >>> >>> print(xl.__doc__) b=xl.Contenitore() dir(b) print b.__doc__

L.Fini - Introduzione al linguaggio Python




Namespace
name2.py

-3

a=2.4142 b=5.44 def sub(): global a a=7 b=7

>>> a=-5.12 >>> import name2 as n2 >>> print a >>> print n2.a >>> print n2.b >>> >>> >>> >>> n2.sub() print a print n2.a print n2.b
L.Fini - Introduzione al linguaggio Python




Namespace
name1.py

-4

a=3.1415 import name2 as n2

>>> a=-5.12 >>> import name1 as n1 >>> dir() >>> print a >>> print n1.a >>> print n1.n2.a >>> >>> >>> >>> n1.n2.sub() print a print n1.a print n1.n2.a

L.Fini - Introduzione al linguaggio Python




Namespace

-5

>>> a=-5.12 >>> from name1 import * >>> dir() >>> print a >>> print n2.a >>> n2.sub() >>> print a >>> print n2.a

L.Fini - Introduzione al linguaggio Python




Stringhe di documentazione
- class4.py

""" Questo package definisce la classe Contenitore """ version=1.5 class Contenitore: """Classe xlist: lista che memorizza elementi di vario tipo (interi, float, stringhe), mantenendoli separati""" def __init__(self): self.__int=[] self.__flt=[] self.__str=[] def append(self,value): "Aggiunge un nuovo valore alla lista" if value is int: self.__int.append(value) elif value is float: self.__flt.append(value) elif value is str: self.__str.append(value) def getint(self): return self.__int def getfloat(self): return self.__flt def getstring(self): return self.__str

L.Fini - Introduzione al linguaggio Python




Moduli standard


sys os
­



os.path



math, cmath random ... e altri 280 ...





L.Fini - Introduzione al linguaggio Python




Modulo sys

sys.argv sys.exit() sys.maxint sys.maxsize sys.path (vedi: PYTHONPATH) sys.platform sys.stdin sys.stdout sys.stderr

L.Fini - Introduzione al linguaggio Python




Modulo os

-1

os.environ os.getenv('HOME') os.tmpfile() os.access('a.py',os.R_OK) os.chdir('newdir') os.listdir('dirname') os.mkdir('/dir1/dir2/name') os.makedirs('/dir1/dir2/name') os.rename('old','new') os.renames('old','new') os.walk('topdir')

L.Fini - Introduzione al linguaggio Python




Modulo os

-2
os.spawnl() os.spawnle()

os.execl() os.execle() ... os.system()

... ...

vedere modulo subprocess

os.devnull

L.Fini - Introduzione al linguaggio Python




Modulo os.path -3

os.path.abspath(path) os.path.basename(path) os.path.dirname(path) os.path.split(path) os.path.commonprefix(list) os.path.exists(path) os.path.getatime(path) os.path.getmtime(path) os.path.getctime(path) os.path.join(path1,path2,..)

L.Fini - Introduzione al linguaggio Python




Altri moduli


math
­

->man.

Notare: fsum, expm1, log1p



cmath
­

->man.

aritmetica complessa



random

->man.

L.Fini - Introduzione al linguaggio Python




Ancora moduli


numpy

->man.



matplotlib ->man.

L.Fini - Introduzione al linguaggio Python




pydb / pdb


Python debugger



idle


Integrated development environmnet per Python



ipython


Interactive Python
L.Fini - Introduzione al linguaggio Python




Verso Python 3


-1

print ­ funzione
(gia' usabile in 2.6)

Old: print "The answer is", 2*2 New: print("The answer is", 2*2) Old: print x, New: print(x,end=" ") Old: print New: print() Old: print >>sys.stderr, "error" New: print("error",file=sys.stderr) Old: print (x, y) New: print((x, y))


3/5

L.Fini - Introduzione al linguaggio Python




Verso Python 3


-2

Quasi nient'altro, fra gli argomenti trattati fin qui, cambia. Uso estensivo di Unicode per le stringhe. Stringhe e sequenze di bytes diventano oggetti diversi. Il tipo long non esiste piu'







L.Fini - Introduzione al linguaggio Python


Python URLs


http://www.python.org http://www.python.it http://www.scipy.org http://www.astropython.org http://spacepy.lanl.gov http://openbookproject.net/pybiblio











L.Fini - Introduzione al linguaggio Python




Case: timemark.py
1 2

3

4 5

6
> python timemark.py (termina: CTRL-D) > ping | ./timemark.py

L.Fini - Introduzione al linguaggio Python




Case: DMS2Deg.py

1

2 3 4!

5

L.Fini - Introduzione al linguaggio Python




Case: CCDSCALE.py

1

2 3 4 5 3

6 5

L.Fini - Introduzione al linguaggio Python




Case: SDSS_getfpC.py

1 2 3 4-5

6

L.Fini - Introduzione al linguaggio Python




Case: scan80.py
2 3

1

4 5 6

7
L.Fini - Introduzione al linguaggio Python




Case: httpsimple.py -1

9

11

12 10 1

2

3
L.Fini - Introduzione al linguaggio Python




Case: httpsimple.py -2

4 7

5 6

8

L.Fini - Introduzione al linguaggio Python




Case: mappine


Vecchio programma FORTRAN (© Andreoni/Forti) difficile da usare Wrapper CGI (in PERL, ma l'esempio vale lo stesso!)
­ ­ ­ ­ ­



riceve gli argomenti dalla pagina Web Crea directory di lavoro Crea il file MAPPINE.DAT Lancia il programma (due volte: sud e nord) Converte il file di output in PDF

Legge dati di input da file: MAPPINE.DAT:
1 'OSSERVATORIO DI ARCETRI' 'Firenze' 43.75 -.75 -1 1999 28 1 27 18 outfile.ps

Genera un file PostScript
L.Fini - Introduzione al linguaggio Python