Python Corso UniMi
Python Corso UniMi
Python Corso UniMi
• Usato da:
Google, Yahoo!, Youtube
Molte distribuzioni Linux
Giochi and app
Recentemente diffuso in ambito
scientifico
2
Installare Python
Windows: Mac OS X:
• Download Python da • Python e’ gia’ installato.
http://www.python.org • Aprite un terminale ed
• Installate Python. eseguite python o lanciate
• Aprite Idle dal menu’ Start. Idle da Finder.
Linux:
• E’ probabile che Python sia
gia’ installato. Verificate
scrivendo python nel
terminale.
• Se non e’ disponibile
installatelo dal sistema di
gestione dei pacchetti della
vostra distribuzione.
3
Linguaggi interpretati
• interpretato
Non compilato come Java, C, C++
Codice scritto ed eseguito direttamente da un
interprete
E’ possibile scrivere comandi direttamente
nell’interprete e osservarne il risultato (come in R)
Python: Compute
Code Interpreter
r
4
L’Interprete Python
• Permette di scrivere comandi uno alla volta ed
osservarne il risultato
• Modo molto comodo di fare esperienza con la
sintassi di Python
5
Primo programma in
Python
• Python non ha un metodo main come Java
Il codice del programma e’ semplicemente scritto nel
file che verra’ eseguito (file sorgente)
• In Python le righe non finiscono con ; (come in PERL)
hello.py
1 print("Hello, world!")
6
La funzione print
print("text")
print() (una linea vuota)
Sequenze di escape come \" sono le stesse di Java
Le stringhe possono iniziare/finire con '
swallows.py
1 print("Hello, world!")
2 print()
3 print("Suppose two swallows \"carry\" it together.")
4 print('African or "European" swallows?')
7
Commenti
• Sintassi:
# testo commentato (una riga)
swallows2.py
8
Funzioni
• Funzioni: Equivalenti di metodi statici in Java (e di funzioni in
R).
• Sintassi hello2.py
9
Significato spazi bianchi
• Python usa le indentazioni per indicare I blocchi di
codice invece di {}
Questo rende il codice piu’ leggibile
In Java l’indentazione e’ opzionale. In Python essa e’
obbligatoria!
hello3.py
10
Esercizio (funzioni)
• Scrivere un programma Python che ricrei questo output:
______
/ \
/ \
\ /
\______/
\ /
\______/
+--------+
______
/ \
/ \
| STOP |
\ /
\______/
______
/ \
/ \
+--------+
11
Soluzione esercizio
def egg(): def top():
top() print(" ______")
bottom() print(" / \\")
print() print("/ \\")
12
Unit 2
Espressioni e variabili; ciclo for
Espressioni
• Aritmetica molto simile a Java e R
Operatori: + - * / %
Precedenza: () quindi ** quindi * / % quindi + -
Numeri interi e numeri reali
>>> 1 + 1
2
>>> 1 + 3 * 4 - 2
11
>>> 7 / 2
3
>>> 7.0 / 2
3.5
>>> 10 ** 6
1000000
14
Operatori aritmetici
Assumendo le variabili a=5 e b=3 :
15
Operatori di assegnazione 1
= assegna Es: a=5 assegna alla variabile a che sta a sinistra il valore 5 (ovvero ciò che
è a destra dell’uguale.) Un altro esempio potrebbe essere a=b+c dove ad a stavolta
assegniamo la somma b+c.
16
Operatori di assegnazione 2
//= divide e assegna Assegna all’operando di sinistra la divisione
arrotondata tra esso e l’operando di destra. Es: a//=2 equivale a fare
a=a//2, quindi assegna alla variabile a che sta a sinistra il valore di a
(supponiamo sempre a=5) diviso 2 arrotondato all’intero. Quindi
otterremo a=2.
17
Variabili
• Dichiarazione
Non si scrive il tipo; stessa sintassi dell’assegnamento
• Operatori
Non esistono operatori ++ o -- operatori (si incrementa
o decrementa di 1)
Java Python
int x = 2; x = 2
x++; x = x + 1
System.out.println(x) print(x)
;
x = x * 8
x = x * 8; print(x)
System.out.println(x)
; d = 3.2
d = d / 2
double d = 3.2; print(d)
d = d / 2;
System.out.println(d)
;
18
Variabili
• Regole di definizione dei nomi di variabile
19
Tipi di variabile
• Python e’ piu’ permissivo di Java
Il tipo di variabile non va dichiarato
Le variabili possono cambiare di tipo durante
l’esecuzione del programma
Value Java Python
type type
42 int int
3.14 double float
"ni!" String str
20
Moltiplicare di stringhe
• Le stringhe Python possono essere moltiplicate per
un valore intero.
Il risultato sono diverse copie concatenate della
stringa.
>>> "hello" * 3
"hellohellohello"
21
Concatenare stringhe
• Interi e stringhe non possono essere concatenate in
Python.
Possibile soluzione:
str(value) - converte valore in stringa
print(expr, expr) - stampa due variabili sulal stessa
linea
>>> x = 4
>>> print("Thou shalt not count to " + x + ".")
TypeError: cannot concatenate 'str' and 'int' objects
22
Il ciclo for
for name in range(max):
statements
23
for Variazioni ...
for name in range(min, max):
statements
for name in range(min, max, step):
statements
Possibile specificare un minimo diverso da 0 ed un step
diverso da 1
>>> for i in range(2, 6):
... print(i)
2
3
4
5
>>> for i in range(15, 0, -5):
... print(i)
15
10
5
24
Cicli annidati
• Cicli annidati sono spesso rimpiazzati da
moltiplocazioni e addizioni tra stringhe
Java
....1
1 for (int line = 1; line <= 5; line++) {
...2 2 for (int j = 1; j <= (5 - line); j++) {
..3 3 System.out.print(".");
4 }
.4 5 System.out.println(line);
5 6 }
Python
25
Esercizio
• Riscrivete il programma Mirror in Python. Il suo
output e’ il seguente:
#================#
| <><> |
| <>....<> |
| <>........<> |
|<>............<>|
|<>............<>|
| <>........<> |
| <>....<> |
| <><> |
#================#
26
Soluzione esercizio
def bar():
print "#" + 16 * "=" + "#"
def top():
for line in range(1, 5):
# Convenzione slide: linee troppo lunghe spezzate da \
print "|" + (-2 * line + 8) * " " + \
"<>" + (4 * line - 4) * "." + "<>" + \
(-2 * line + 8) * " " + "|"
def bottom():
for line in range(4, 0, -1):
print "|" + (-2 * line + 8) * " " + \
"<>" + (4 * line - 4) * "." + "<>" + \
(-2 * line + 8) * " " + "|"
# main
bar()
top()
bottom() NON INSERITE IL CARATTERE \ NEL SORGENTE!
bar()
27
Concatenazione di range
• I range possono essere concatenati con il +
E’ possibile ciclare attraverso insiemi disgiunti di
numeri
28
Soluzione esercizio
def bar():
print "#" + 16 * "=" + "#"
def top():
for line in range(1, 5):
# Convenzione slide: linee troppo lunghe spezzate da \
print "|" + (-2 * line + 8) * " " + \
"<>" + (4 * line - 4) * "." + "<>" + \
(-2 * line + 8) * " " + "|"
def bottom():
for line in range(4, 0, -1):
print "|" + (-2 * line + 8) * " " + \
"<>" + (4 * line - 4) * "." + "<>" + \
(-2 * line + 8) * " " + "|"
# main
bar()
top()
bottom() NON INSERITE IL CARATTERE \ NEL SORGENTE!
bar()
29
Esercizio: soluzione 2
def bar():
print "#" + 16 * "=" + "#"
def mirror():
for line in range(1, 5) + range(4, 0, -1):
print "|" + (-2 * line + 8) * " " + \
"<>" + (4 * line - 4) * "." + "<>" + \
(-2 * line + 8) * " " + "|"
# main
bar()
mirror()
bar()
30
Costanti
• Python non ha delle vere e proprie costanti.
Dichiariamo una variabile “globale” al di sopra del
codice principale.
Tutti I metodi potranno usare questa variabile.
constant.py
1 MAX_VALUE = 3
2
3 def printTop():
4 for i in range(MAX_VALUE):
5 for j in range(i):
6 print(j)
7 print()
8
9 def printBottom():
10 for i in range(MAX_VALUE, 0, -1):
11 for j in range(i, 0, -1):
12 print(MAX_VALUE)
13 print()
31
Esercizio: soluzione 3
SIZE = 4
def bar():
print "#" + 4 * SIZE * "=" + "#"
def mirror():
for line in range(1, SIZE + 1) + range(SIZE, 0, -1):
print "|" + (-2 * line + 2 * SIZE) * " " + \
"<>" + (4 * line - 4) * "." + "<>" + \
(-2 * line + 2 * SIZE) * " " + "|"
# main
bar()
mirror()
bar()
32
Unit 3
parameteri di funzione
Parametri di funzioni
def name(parameter, parameter, ...,
parameter):
statements
>>> print_many("hello", 4)
hello
hello
hello
hello
34
Esercizio
• Ricreate questa serie di asterischi che disegnano
linee e barre (rettangoli):
*************
*******
***********************************
**********
* *
**********
*****
* *
* *
*****
35
Soluzione esercizio
stars.py
36
Valori di default
def name(parameter=value, ..., parameter=value):
statements
Potete rendere I parametri opzionali specificando un valore di
default
37
Nomi dei parametri
name(parameter=value, ..., parameter=value)
E’ possibile specificare I nomi dei parametri durante la
ciamata della funzione
Questo permette di passare I parametri in qualsiasi
ordine
>>> def print_many(str, n):
... for i in range(n):
... print(str)
40
Restituire valori
def name(parameters):
statements
...
return expression
>>> ftoc(98.6)
37.0
41
input
input : Legge una stringa dalla tastiera.
– Legge e restituisce un’intera riga di input *
>>> name
'Mario Rossi'
42
input
• Per leggere numeri, convertire il risultato di input() in
un int o in un float
– Se l’utente non inserisce un numero viene generato un
errore.
– Esempio:
age = int(input("How old are you? "))
print("Your age is", age)
print(65 - age, "years to retirement")
Output:
How old are you? 53
Your age is 53
12 years to retirement
43
if
if condition:
statements
Esempio:
gpa = float(input("What is your GPA? "))
if gpa > 2.0:
print("Your application is accepted.")
44
if/else
if condition:
statements
elif condition:
statements
else:
statements
Example:
gpa = float(input("What is your GPA? "))
if gpa > 3.5:
print("You have qualified for the honor roll.")
elif gpa > 2.0:
print("Welcome to Mars University!")
else:
print("Your application is denied.")
45
if ... in
if value in sequence:
statements
Esempi:
x = 3
if x in range(0, 10):
print("x is between 0 and 9")
46
Operatori logici
Operator Meaning Example Result
== equals 1 + 1 == 2 True
!= does not equal 3.2 != 2.5 True
< less than 10 < 5 False
> greater than 10 > 5 True
<= less than or equal to 126 <= 100 False
>= greater than or equal to 5.0 >= 5.0 True
47
Esercizio
• Scrivi un programma che legga le ore lavorate da
due impiegati e scriva il totale e la media giornaliera
(per impiegato) ed il totale di ore lavorate.
Riduci le ore inserite dall’utente ad un massimo di 8.
Employee 1: How many days? 3
Hours? 6
Hours? 12
Hours? 5
Employee 1's total hours = 19 (6.33 / day)
48
Stringhe
index 0 1 2 3 4 5 6 7
or -8 -7 -6 -5 -4 -3 -2 -1
charact P . D i d d y
er
>>> name = "P. Diddy"
>>> name[0]
• Accesso ai caratteri: 'P'
variable [ index ] >>> name[7]
'y'
variable [ index1:index2 ] >>> name[-1]
'y'
>>> name[3:6]
index2 exclusive 'Did'
>>> name[3:]
index1 or index2 can be 'Diddy'
omitted (goes to end of string) >>> name[:-2]
'P. Did'
49
Metodi delle stringhe
Java Python
length len(str)
trim strip
51
Formattazione del testo
"format string" % (parameter, parameter, ...)
• Segnaposto inseriscono valori formattati in una stringa:
– %d an integer
– %f a real number
– %s a string
– %8d an integer, 8 characters wide, right-aligned
– %08d an integer, 8 characters wide, padding with 0s
– %-8d an integer, 8 characters wide, left-aligned
– %12f a real number, 12 characters wide
– %.4f a real number, 4 characters after decimal
– %6.2f a real number, 6 total characters wide, 2 after
decimal
>>> x = 3; y = 3.14159; z = "hello"
>>> print "%-8s, %04d is close to %.3f" % (z, x, y)
hello , 0003 is close to 3.142
52
Stringhe e interi
• ord(text) - Converte una stringa in un numero.
– ord("a") is 97
– ord("b") is 98
53
Crittografia di base
• Cifrario a rotazione – scambia ogni lettera di un numero
prefissato di posizioni
Cifrario di Cesare – scambia ogni lettera di 3 passi (in avanti)
"the cake is a lie" diventa
"wkh fdnh lv d olh"
54
Exercise
• Scivere un programma che critti un messaggio segreto
usando un cifrario di Cesare shiftando le lettere di 3 posizioni
(in avanti):
es. "Attack" se rotato di 2 diventa "cwwcfn"
55
Unit 5
Ciclo while ; flusso logico del
programma; numeri casuali; tuple
Ciclo while
while test:
statements
sentinel.py
57
Random Numbers
from random import *
randint(min, max)
Ritorna un intero casuale nel range [min, max] inclusi
choice(sequence)
Restituisce una valore scelto a caso dalla sequenza
data
(la sequenza puo’ essere un range, una stringa, un
array, ...)
>>> from random import *
>>> randint(1, 5)
2
>>> randint(1, 5)
5
>>> choice(range(4, 20, 2))
16
>>> choice("hello")
'e' 58
while / else
while test:
statements
else:
statements
Esegue la parte else se non si entra mai in loop
Esosre uno statement for / else simile
>>> n = 91
>>> while n % 2 == 1:
... n += 1
... else:
... print(n, "was even; no loop.")
...
91 was even; no loop.
59
bool
• E’ il tipo di dato logico di Python, equivalente ai
boolean in Java
– True e False iniziano con lettere maiuscole
>>> 5 < 10
True
>>> b = 5 < 10
>>> b
True
>>> if b:
... print("The value is true")
...
The value is true
>>> b = not b
>>> b
False
60
Operatori logici
Operator Meaning Example Result
== equals 1 + 1 == 2 True
!= does not equal 3.2 != 2.5 True
< less than 10 < 5 False
> greater than 10 > 5 True
<= less than or equal to 126 <= 100 False
>= greater than or equal to 5.0 >= 5.0 True
61
Esercizio
• Scrivere il programma Dice in Python. Il suo output
e’ il seguente (vittoria se due dadi restituiscono
valori casuali che sommano a 7).
2 + 4 = 6
3 + 5 = 8
5 + 6 = 11
1 + 1 = 2
4 + 3 = 7
You won after 5 tries!
62
Tuple
tuple_name = (value, value, ..., value)
Modo comodo per "impacchettare" piu’ valori in
un’unica variabile
>>> x = 3
>>> y = -5
>>> p = (x, y, 42)
>>> p
(3, -5, 42)
65
Tuple come valori di ritorno
def name(parameters):
statements
return (name, name, ..., name)
66
Unit 6
Processamento di file
Leggere File
name = open("filename")
Apre il file di cui e’ fornito il percorso in lettura e
ritorna un oggetto di tipo file.
name = open("filename")
for line in name:
statements
69
Esercizio
• Scrivere una funzione input_stats che accetta in
input il fome di un file e ritorna la riga piu’ lunga del
file.
Esempio di input file, carroll.txt:
Beware the Jabberwock, my son,
the jaws that bite, the claws that catch,
Beware the JubJub bird and shun
the frumious bandersnatch.
Output atteso:
>>> input_stats("carroll.txt")
longest line = 42 characters
the jaws that bite, the claws that catch,
70
Soluzione esercizio
def input_stats(filename):
input = open(filename)
longest = ""
for line in input:
if len(line) > len(longest):
longest = line
71
Ripasso: Metodi stringhe
Java Python
length len(str)
trim strip
ord, chr
75
Soluzione Esercizio
hours.py
1 input = open("hours.txt")
2 for line in input:
3 id, name, mon, tue, wed, thu, fri = line.split()
4
5 # Somma cumulativa delle ore di questo impiegato
6 hours = float(mon) + float(tue) + float(wed) + \
7 float(thu) + float(fri)
8
9 print(name, "ID", id, "worked", \
10 hours, "hours: ", hours/5, "/ day"
76
Scrivere su File
name = open("filename", "w")
name = open("filename", "a")
Apre file in lettura (cancella contenuto), o
Apre file per aggiungere righe (nuovi dati inseriti in
coda al file)
78
Unit 7
Liste
Liste
• liste: equivalenti Python degli array Java (ma
migliori)
Dichiarazione:
name = [value, value, ..., value] or,
name = [value] * length
index 0 1 2 3 4 5 6 7
value 9 14 12 19 16 7 24 15
index -8 -7 -6 -5 -4 -3 -2 -1
81
Richiamo: Stringhe
index 0 1 2 3 4 5 6 7
value P . D i d d y
-index -8 -7 -6 -5 -4 -3 -2 -1
82
Slicing
• slice: Una sotto-lista creata specificando indice start
e indice stop
name[start:end] # end e’ escluso
name[start:] # fino a fine lista
name[:end] # da inizio lista
name[start:end:step] # ogni step-esimo valore
>>> scores = [9, 14, 12, 19, 16, 18, 24, 15]
>>> scores[2:5]
[12, 19, 16]
>>> scores[3:] inde 0 1 2 3 4 5 6 7
[19, 16, 18, 24, 15] x
>>> scores[:3]
[9, 14, 12] value 9 14 12 19 16 18 24 15
>>> scores[-3:] inde -8 -7 -6 -5 -4 -3 -2 -1
[18, 24, 15] x
83
Liste
Le liste si pososno stampare (o converire in stringhe
con str()).
Lunghezza calcolata tramite funzione len .
Ciclare attraverso unalista usando un loop for ... in .
>>> scores = [9, 14, 18, 19]
>>> print("My scores are", scores)
My scores are [9, 14, 18, 19]
>>> len(scores)
4
>>> total = 0
>>> for score in scores:
... print("next score:", score)
... total += score
next score: 9
next score: 14
next score: 18
next score: 19
>>> total
60 84
Range, Stringhe, e Liste
• La funzione range ritorna una lista.
>>> nums = range(5)
>>> nums
[0, 1, 2, 3, 4]
>>> nums[-2:]
[3, 4]
>>> len(nums)
5
85
Splitting di stringhe
• split spezza una stringa in una lista di elementi.
name.split() # break by whitespace
name.split(delimiter) # break by delimiter
86
Tokenizzazione File Input
• Use split per tokenizzare il contenuto delle righe
lette da file.
Se e’ necessaria una conversione: type(value)
>>> f = open("example.txt")
>>> line = f.readline()
>>> line
'hello world 42 3.14\n'
88
Soluzione Esercizio
hours.py
1 file = open("hours.txt")
2 for line in file:
3 tokens = line.split()
4 id = tokens[0]
5 name = tokens[1]
6
7 # somma cumulativa delle ore di questo impiegato
8 hours = 0.0
9 days = 0
10 for token in tokens[2:]:
11 hours += float(token)
12 days += 1
13
14 print(name, "ID", id, "worked", \
15 hours, "hours:", hours / days, "/ day")
89
Esercizio
• Supponiamo di avere un file contenente I punteggi
ottenuti durante un parziale di meta’ corso, scores.txt:
76
89
76
72
68
90
Esercizio
• Supponiamo di avere dati scaricati da Internet Movie
Database (IMDb):
1 9.1 196376 The Shawshank Redemption (1994)
2 9.0 139085 The Godfather: Part II (1974)
3 8.8 81507 Casablanca (1942)
91
Soluzione Esercizio
movies.py
92
Unit 8
Classi e Oggetti; Ereditarieta’
OOP, Definire una Classe
• Python e’ stato costruito come linguaggio
procedurale ma
OOP (object orientedprogramming) esiste e funziona
bene
94
Campi (var. interne)
name = value
Esempio: point.py
class Point: 1 class Point:
x = 0 2 x = 0
y = 0 3 y = 0
# main
p1 = Point()
p1.x = 2
p1.y = -5
95
Using a Class
import class
Programmi client (utenti di classi esterne) DEVONO
importare TUTTE le classi che usano.
point_main.py
96
Metodi degli oggetti
def name(self, parameter, ..., parameter):
statements
class Point:
def translate(self, dx, dy):
self.x += dx
self.y += dy
...
97
Parametro "Implicito"
(self)
• Java: this, implicito
public void translate(int dx, int dy) {
x += dx; // this.x += dx;
y += dy; // this.y += dy;
}
98
Soluzione Esercizio
point.py
99
Chiamate a Metodi
• Il programma client puo’ chiamare I metodi di un
oggetto in due modi:
(il valore di self puo’ essere un parametro esplicito o
implicito)
1) object.method(parameters)
oppure
2) Class.method(object, parameters)
• Esempio:
p = Point(3, -4)
p.translate(1, 5)
Point.translate(p, 1, 5)
100
Costruttori di classe
def __init__(self, parameter, ..., parameter):
statements
Esempio:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
...
101
toString and __str__
def __str__(self):
return string
Equivalente del metodo toString di Java (converte
oggetto in stringa)
invicato automaticamente quanso str o print
vengono usate sull’oggetto
102
Classe Point completa
point.py
1 from math import *
2
3 class Point:
4 def __init__(self, x, y):
5 self.x = x
6 self.y = y
7
8 def distance_from_origin(self):
9 return sqrt(self.x * self.x + self.y * self.y)
10
11 def distance(self, other):
12 dx = self.x - other.x
13 dy = self.y - other.y
14 return sqrt(dx * dx + dy * dy)
15
16 def translate(self, dx, dy):
17 self.x += dx
18 self.y += dy
19
20 def __str__(self):
21 return "(" + str(self.x) + ", " + str(self.y) + ")"
103
Operator Overloading
• operator overloading: You can define functions so
that Python's built-in operators can be used with
your class.
• See also: http://docs.python.org/ref/customization.html
Operator Class Method Operator Class Method
- __neg__(self, other) == __eq__(self, other)
+ __pos__(self, other) != __ne__(self, other)
* __mul__(self, other) < __lt__(self, other)
/ __truediv__(self, other) > __gt__(self, other)
Unary Operators
- __neg__(self) <= __le__(self, other)
104
Esercizio
• Esercizio: Scrivere una classe Fraction per rappresentare
numeri razionali come 1/2 e -3/8.
105
Generare Eccezioni
raise ExceptionType("message")
Esempio:
class BankAccount:
...
def deposit(self, amount):
if amount < 0:
raise ValueError("negative amount")
...
106
Ereditarieta’
class name(superclass):
statements
Esempio:
class Point3D(Point): # Point3D estende Point
z = 0
...
(NB: se piu’ superclassi hanno gli stessi campi/metodi, I conflitti sono risolti da sinistra a
destra seguendo l’ordine nella definizione della classe)
107
Chiamare metodi delle
Superclassi
• metodi: class.method(object,
parameters)
• costruttori: class.__init__(parameters)
class Point3D(Point):
z = 0
def __init__(self, x, y, z):
Point.__init__(self, x, y)
self.z = z
108