Python Corso Dinitto
Python Corso Dinitto
di Milano
Coding in Python
Tutor
Lezioni Gianmarco Loliva (mattina e
Elisabetta Di Nitto pomeriggio)
Via Golgi, 42 email [email protected]
email [email protected] Marco Arquati (pomeriggio)
tel: 02-2399-3663 email [email protected]
http://dinitto.faculty.polimi.it
7
…a macchine programmabili…
8
…a macchine programmabili un po’ più
maneggevoli…
6/9/19 9
…a???
6/9/19 https://www.youtube.com/watch?v=avP5d16wEp0
10
Utenti, computer, reti, programmatori
Alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r',
's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
notAPangram = False
if notAPangram:
print('the string is not a pangram')
else:
print('the string is a pangram')
Programmi, esecutori e linguaggi di
programmazione
http://upload.wikimedia.org/wikipedia/commons/3/3d/RaspberryPi.jpg
Il modello di Von Neumann
Bus
0101 Conserva in 1010 il valore che si trova in A
0010000000001010
0110 Stampa il contenuto di 1010
0101000000001010
0111 1101000000000000 Termina l’esecuzione
1000 X
1001 Y
1010 Z
Linguaggio macchina vs altri linguaggi di
programmazione
???
Programma
in C
Programma in
Programma Compilatore linguaggio
in C
macchina
Programma in
Programma Compilatore linguaggio
in C
macchina
Istruzione in
Programma Interprete linguaggio
in Python
macchina
Interprete Python
Può essere scaricato e istallato da qui
https://www.python.org
Vari ambienti di programmazione
Spyder
Jupyter
Anaconda
https://www.pythonanywhere.com
30
Elementi di Python
x = 12.2 x 12.2
y = 14
y 14
Variabili
x = 12.2
x 12.2 100
y = 14
x = 100
y 14
Frasi
Operatore
Variabile Costante
Istruzione di assegnamento
x = 2
x = x + 2 Assegnamento con espressione
print(x) Istruzione di stampa
Funzione
Flusso del programma
x = 2 Programma:
Output:
print(x) x = 2
print(x) 2
x = x + 2 x = x + 2 4
print(x)
print(x)
x = 5
Yes
x < 10 ?
print('Smaller') Program:
No Output:
x = 5
Yes if x < 10: Smaller
x > 20 ? print('Smaller') Finis
if x > 20:
print('Bigger') print('Bigger')
No
print('Finis')
print('Finis')
Istruzioni ripetute
n = 5
No Yes Output:
n > 0 ? Program:
5
print(n) n = 5 4
while n > 0 :
print(n)
3
n = n -1 n = n – 1 2
print('Blastoff!') 1
Blastoff!
I cicli (istruzioni ripetute) utilizzano una o più variabili che
print('Blastoff')
controllano l’esecuzione del ciclo.
Classifichiamo le istruzioni del nostro
primo esempio…
text = input('Write a sentence: ')
Alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r',
's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
notAPangram = False
if notAPangram: Sequenziale
print('the string is not a pangram')
else: Ciclo
print('the string is a pangram') Condizionale
% Remainder
Che cosa significa “tipo”?
In Python variabili e
costanti hanno un “tipo”
Per esempio, numeri e
stringhe sono tipi diversi
>>> ddd = 1 + 4
Il risultato di >>> print(ddd)
un’espressione dipende da 5
>>> eee = 'hello ' + 'there'
tipo degli operandi >>> print(eee)
L’operazione “+” significa hello there
addizione se applicata a
numeri e concatenazione
se applicata a stringhe
Ogni valore ha un tipo
>>> xx = 1
Esistono due tipi principali di >>> type (xx)
numeri <class 'int'>
Interi: >>> temp = 98.6
>>> type(temp)
-14, -2, 0, 1, 100, 401233 <class'float'>
Numeri con la virgola (Floating >>> type(1)
Point Numbers) : <class 'int'>
>>> type(1.0)
-2.5 , 0.0, 98.6, 14.0
<class'float'>
>>>
Divisione intera
Esecuzione
Who are you? Chuck
Welcome Chuck
Convertire l’input dell’utente
Se vogliamo acquisire
un numero, dobbiamo inp = input('Europe floor?')
convertire il risultato di usf = int(inp) + 1
input da stringa a intero print('US floor', usf)
Europe floor? 0
US floor 1
Commenti in Python
x = 5
Yes
x < 10 ?
print('Smaller') Programma:
No Output:
x = 5
Yes if x < 10: Smaller
x > 20 ? print('Smaller') Finis
if x > 20:
print('Bigger') print('Bigger')
No
print('Finis')
print('Finis')
Operatori di confronto
x = 5
if x > 2 :
print('Bigger than 2')
print('Still bigger')
print('Done with 2')
for i in range(5) :
print(i)
if i > 2 :
print('Bigger than 2')
print('Done with i', i)
print('All Done')
Else
x = 4
no yes
x = 4 x > 2
if x > 2 :
print('Bigger') print('Not bigger') print('Bigger')
else :
print('Smaller')
print('All done')
print('All Done')
Else if -> elif
if x < 2 :
print('Small')
elif x < 10 :
# No Else print('Medium')
x = 5 elif x < 20 :
if x < 2 : print('Big')
print('Small') elif x < 40 :
elif x < 10 : print('Large')
print('Medium') elif x < 100:
print('Huge')
print('All done') else :
print('Ginormous')
Esercizio
n = 5
No Yes Output:
n > 0 ? Program:
5
print(n) n = 5 4
while n > 0 :
print(n)
3
n = n -1 n = n – 1 2
print('Blastoff!') 1
Blastoff!
I cicli (istruzioni ripetute) utilizzano una o più variabili che
print('Blastoff')
controllano l’esecuzione del ciclo.
Definite loop
Lista di numeri
5
for i in [5, 4, 3, 2, 1] :
print(i)
4
print(’Fine!') 3
2
1
Fine!
Un definite loop con le stringhe
Lista di stringhe
Impiegato 1
Inserisci il numero di ore: 45
Inserisci la paga oraria: 10
Impiegato 2
Inserisci il numero di ore: 32
Inserisci la paga oraria: 12
Per x == 4
I am in the loop 4
while x > 0 : I am in the loop 3
print('I am in the loop', x) I am in the loop 2
x = x -1 I am in the loop 1
I am in the else 0
else :
I am out of the loop
print('I am in the else', x)
print('I am out of the loop')
Part of these slides are Copyright 2010- Charles R. Severance (www.dr-chuck.com) of the
University of Michigan School of Information and made available under a Creative Commons
Attribution 4.0 License.
Coding in Python
Lezione 2
STRINGS
Looking Inside Strings
fruit = 'banana' 0 b
index = 0 1 a
while index < len(fruit): 2 n
letter = fruit[index] 3 a
print(index, letter) 4 n
index = index + 1
5 a
Looping Through Strings
b
fruit = 'banana' a
for letter in fruit: n
print(letter) a
n
a
Slicing Strings
M o n t y P y t h o n
We can also look at
0 1 2 3 4 5 6 7 8 9 10 11
any continuous section >>> s = 'Monty Python'
of a string using a colon >>> print(s[0:4])
operator ‘Mont’
The second number is >>> print(s[6:8])
‘Py’
one beyond the end of >>> print(s[:2])
the slice - “up to but not ‘Mo’
including” >>> print(s[8:])
‘thon’
If the second number is
>>> print(s[:])
beyond the end of the ‘Monty Python’
string, it stops at the >>> print(s[7:3:-1])
end ‘yP y’
>>> print(s[::-1])
‘nohtyP ytnoM’
Exercise
>>> a = 'Hello'
>>> b = a + 'There'
>>> print(b)
HelloThere
>>> c = a + ' ' + 'There'
>>> print(c)
Hello There
>>>
Using in as a Logical Operator
The in keyword can also be used to check to see if
one string is “in” another string
The in expression is a logical expression that returns
True or False and can be used in an if statement
>>> fruit = 'banana'
>>> 'n' in fruit
True
>>> 'm' in fruit
False
>>> 'nan' in fruit
True
>>> if 'a' in fruit :
... print('Found it!')
...
Found it!
>>>
String Library
https://docs.python.org/3/library/stdtypes.html#string-methods
String Library
Searching a String
21 31
5
for i in [5, 4, 3, 2, 1] :
print(i)
4
print('Blastoff!') 3
2
1
Blastoff!
Looking Inside Lists
Just like strings, we can get at any single element in
a list using an index specified in square brackets
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = a + b
>>> print(c)
[1, 2, 3, 4, 5, 6]
>>> print(a)
[1, 2, 3]
Lists Can Be Sliced Using :
>>> x = list()
>>> type(x)
<type 'list'>
>>> dir(x)
['append', 'count', 'extend', 'index', 'insert',
'pop', 'remove', 'reverse', 'sort']
>>>
http://docs.python.org/tutorial/datastructures.html
Building a List from Scratch
Python provides two operators that let you check if an
item is in a list
These are logical operators that return True or False
They do not modify the list
>>> res = [] # or res = list() Python executes an iteration across L
>>> for x in L :
… res.append(x+10)
Comprehensions are typically a lot faster
than using for loops explicitly
Example
A numerical value
corresponding to ‘a’
Strings are immutable and lists are
mutable
Strings are “immutable” - we cannot change the
contents of a string - we must make a new string to
make any change
Lists are “mutable” - we can change an element of a
list using the index operator
From https://medium.com/@meghamohan/mutable-
and-immutable-side-of-python-c2145cf72747
Built-in Functions and Lists
Split breaks a string into parts and produces a list of strings. We think of these
as words. We can access a particular word or loop through all the words.
Best Friends: Strings and Lists
words = line.split()
email = words[1]
The Double Split Pattern
words = line.split()
email = words[1] [email protected]
print email
The Double Split Pattern
words = line.split()
email = words[1] [email protected]
pieces = email.split('@') ['stephen.marquard', 'uct.ac.za']
print pieces[1]
The Double Split Pattern
words = line.split()
email = words[1] [email protected]
pieces = email.split('@') ['stephen.marquard', 'uct.ac.za']
print(pieces[1]) 'uct.ac.za'
FILES
Where are files?
Bus
A text file can be thought of as a sequence of lines
Details: http://source.sakaiproject.org/viewsvn/?view=rev&rev=39772
http://www.py4e.com/code/mbox-short.txt
Opening a File
Before we can read the contents of the file, we must
tell Python which file we are going to work with and
what we will be doing with the file
This is done with the open() function
open() returns a “file handle” - a variable used to
perform operations on the file
Similar to “File -> Open” in a Word Processor
File handles are not numbers, sequences or
mappings and they do not respond to expression
operators
Common file operations
modes
>>> aFile = open(filename, mode) read(r), write(w), append(a)
>>> aFile.method() binary(b)
both input and output (+)
Using files
>>> myFile.open(‘myFile.txt’)
>>> myFile.readline()
‘hello text file\n’ >>> for line in open(‘myFile.txt’):
>>> myFile.readline() print(line)
‘goodbye text file\n’
hello text file
>>> myFile.readline()
goodbye text file
‘’
Esercizio
http://www.hangman.no
Altri esercizi
Part of these slides are Copyright 2010- Charles R. Severance (www.dr-chuck.com) of the
University of Michigan School of Information and made available under a Creative Commons
Attribution 4.0 License.
Initial Development: Charles Severance, University of Michigan School of Information
Adaptation and extensions for the Geo-Python Lab needs: Elisabetta Di Nitto, Politecnico di Milano
Other slides have been adapted from material by my colleague Prof. Sam Guinea, Politecnico di
Milano