Il 0% ha trovato utile questo documento (0 voti)
24 visualizzazioni

Python Corso Dinitto

Caricato da

weben.fad
Copyright
© © All Rights Reserved
Formati disponibili
Scarica in formato PDF, TXT o leggi online su Scribd
Il 0% ha trovato utile questo documento (0 voti)
24 visualizzazioni

Python Corso Dinitto

Caricato da

weben.fad
Copyright
© © All Rights Reserved
Formati disponibili
Scarica in formato PDF, TXT o leggi online su Scribd
Sei sulla pagina 1/ 125

Politecnico

di Milano

Coding in  Python

10-­14  Giugno  2019


Obiettivo

Imparare i concetti di  base  della programmazione


Imparare a  usare Python  come  linguaggio di  
programmazione
Imparare a  risolvere piccoli problemi di  
programmazione
Persone  coinvolte

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

Aspetti  logistici  e  amministrativi


Barbara  Di  Santo
Via  Ponzio  34/5
email  scuole-­[email protected]
tel:  02-­2399-­9607
Organizzazione del  laboratorio

Mattina dalle 9.00  alle 12.30  


Lezioni
Pomeriggio dalle 13.30  alle 17.00
Studio  autonomo e  svolgimento di  esercizi guidato dai
tutor
Aula  G.0.1
Materiale

Libri online  in  Inglese


www.py4e.com
http://docs.python-­guide.org/en/latest/ (argomenti più
avanzati)
Slide  del  corso
CHE COSA È LA  
PROGRAMMAZIONE (O  
CODING)?
Un  po’  di  storia:  da  macchine per  
svolgere un  solo  compito…

By Alessandro Nassiri - Museo della Scienza e della Tecnologia "Leonardo da Vinci",


CC BY-SA 4.0, https://commons.wikimedia.org/w/index.php?curid=47910919

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

• I  programmatori trasformano i dati in  


informazioni,  secondo  quanto necessario
agli utenti
• Devono tenere conto di  tanti vincoli
• I  computer  e  la  rete  sono i loro alleati
Software,  codice e  programmi

Una  sequenza di  istruzioni


Può essere usato più volte  per  svolgere un  certo
compito
Può essere un  pezzo d’arte creativa!  
Programmi per  umani
Programmi per  umani
Programmi per  umani

Divisione tra polinomi


Programmi per  il computer  …  
Un  esempio in  Python

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

for letter in Alphabet:


if letter not in text:
notAPangram = True

if notAPangram:
print('the string is not a pangram')
else:
print('the string is a pangram')
Programmi,  esecutori e  linguaggi di  
programmazione

L’esecutore di  un  programma deve essere capace di  


capire il programma e  di  eseguirne le  istruzioni
Il  programma deve essere definito in  un  linguaggio
che l’esecutore capisce e  di  cui  sa eseguire le  
istruzioni
Qual  è  il  linguaggio  compreso  da  un  computer?  
Che cosa è un  computer?

http://upload.wikimedia.org/wikipedia/commons/3/3d/RaspberryPi.jpg
Il  modello di  Von  Neumann

Bus

Central Main Peripheral Peripheral


Processing Memory Interface I1 Interface In
Unit
Rappresentazione  dell’informazione

Codifica  in  forma  binaria  con  sequenze  finite  di  1  e  0


Unità  minima  di  informazione:  bit  (binary  digit)
Byte:  8  bit
Posso  usarlo  per  rappresentare  28 valori  diversi  (00000000,  
00000001,  00000010,  …,  11111111)
Esempi
Numeri  naturali:  intervallo  [0,  255].  255  =  28-­1
Numeri  interi:  posso  usare  un  bit  per  il  segno  e  7  per  rappresentare  
il  numero.  Intervallo  [-­127  (-­(2(8-­1)-­1)),  +127  (2(8-­1)-­1)]
Caratteri:  codifica  ASCII  (American  Standard  Code  for  Information  
Interchange)  
“a”:  01100001
“0”:  00110000
Esempio di  un  programma scritto nel linguaggio
del  calcolatore (versione semplificata)

0000 0100000000001000 Acquisisci il primo  numero e  conservalo in  1000

0001 0100000000001001 Acquisisci  il  secondo  numero  e  conservalo  in  1001

0010 0000000000001000 Carica in  A  il numero conservato in  1000

0011 0001000000001001 Carica  in  B  il  numero  conservato  in  1001

0100 0110000000000000 Effettua  la  somma

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

Il  linguaggio macchina è poco espressivo


Un  compito semplice deve essere decomposto in  più
istruzioni macchina
I  linguaggi di  programmazione di  “alto  livello” offrono
una maggiore espressività e  semplicità
Python,  C,  Java,  C++,  MATLAB…
Come  fa  la  nostra  macchina ad  eseguire
programmi in  linguaggio di  alto  livello?
Un  programma scritto in  un  linguaggio di  alto  livello NON  è
direttamente eseguibile dal  calcolatore

???
Programma
in  C

q Ci vuole un traduttore, il compilatore

Programma in
Programma Compilatore linguaggio
in  C
macchina

q NB: il compilatore di solito è esso stesso un programma


eseguito dal calcolatore
Come  fa  la  nostra  macchina ad  eseguire
programmi in  linguaggio di  alto  livello?

q Soluzione 1 – Compilatore: trasforma un programma


in linguaggio macchina

Programma in
Programma Compilatore linguaggio
in  C
macchina

q NB: il compilatore di solito è esso stesso un


programma eseguito dal calcolatore
Come  fa  la  nostra  macchina ad  eseguire
programmi in  linguaggio di  alto  livello?

Soluzione 2  – Interprete:  legge e  traduce  al  volo


durante l’esecuzione

Istruzione in  
Programma Interprete linguaggio
in  Python  
macchina

Il  compilatore traduce  il programma PRIMA  


dell’esecuzione,  l’interprete lo  fa  DURANTE  
l’esecuzione
Ambienti  di  programmazione

Forniscono strumenti a  supporto della


programmazione
In  genere offrono
Editor  per  scrivere i programmi
Compilatore:  crea un  codice oggetto per  ogni parte  del  
programma
Linker:  collega le  varie parti del  programma creando un  
unico eseguibile
Debugger:  consente il controllo del  programma durante
la  sua esecuzione
Oppure interprete
PYTHON  COME  LINGUAGGIO
DI  PROGRAMMAZIONE
Python  è il linguaggio dell’interprete Python  e  
di  quelli che vogliono avere una
conversazione  con  questo interprete.  
Una  persona  che può parlare Python  è
chiamata Pythonista.  
Il  primo  interprete è stato sviluppato da  
Guido  van  Rossum.
Errori sintattici:  noi e  il computer

Dobbiamo imparare un  nuovo linguaggio


Faremo tanti errori
Il  computer  non  sarà comprensivo.  Ci  dirà “syntax  
error”.  Ci  sembrerà crudele.
Ricordiamo:  
è più semplice per  noi imparare Python  che per  il
computer  imparare l’Italiano (o  l’Inglese)
noi siamo quelli intelligenti e  pazienti!  
Strumenti  per  usare  Python

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

Vocabolario:  parole  riservate e  variabili

Struttura delle frasi:  istruzioni

Struttura della storia:  costruire un  programma che ha  


uno scopo
Parole  riservate

Parole  che hanno un  significato specifico

False class return is finally


None if for lambda continue
True def from while nonlocal
and del global not with
as elif try or yield
assert else import pass
break except in raise
Variabili

Una  variabile corrisponde a  una posizione nella memoria del  


calcolatore
Può essere usata dai programmatori per  immagazinare dati e  
poi  recuperarli
I  programmatori attribuiscono un  nome a  ciascuna variabile (non  
possono usare le  parole  riservate come  nomi di  variabile)
Il  contenuto di  una variabile può cambiare nel tempo

Programma Memoria  del  calcolatore

x = 12.2 x 12.2
y = 14
y 14                              
Variabili

Una  variabile corrisponde a  una posizione nella memoria del  


calcolatore
Può essere usata dai programmatori per  immagazinare dati e  
poi  recuperarli
I  programmatori attribuiscono un  nome a  ciascuna variabile (non  
possono usare le  parole  riservate come  nomi di  variabile)
Il  contenuto di  una variabile può cambiare nel tempo

Programma Memoria  del  calcolatore

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

Come  una ricetta,  un  programma è una sequenza di  


istruzioni che devono essere eseguite in  un  certo
ordine.
Alcune istruzioni sono condizionali – possono
essere saltate sotto  certe condizioni.
A  volte,  un’istruzione o  un  gruppo di  istruzioni devono
essere ripetute.
A  volte,  raggruppiamo un  insieme di  istruzioni che
devono essere usate in  più punti di  un  programma o  
anche in  programmi diversi (queste sono le  
funzioni).
Sequenza di  istruzioni

x  =  2 Programma:
Output:
print(x) x = 2
print(x) 2
x  =  x  +  2 x = x + 2 4
print(x)
print(x)

Quando un  programma viene eseguito,  le  istruzioni di  cui  è


costituito vengono eseguite in  ordine.    Come  programmatori,  noi
definiamo i “percorsi”  che il programma deve seguire.
Istruzioni condizionali

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

for letter in Alphabet:


if letter not in text:
notAPangram = True

if notAPangram: Sequenziale
print('the string is not a pangram')
else: Ciclo
print('the string is a pangram') Condizionale

Questa  è una breve  storia in  Python  che ci  dice  come  riconoscere


un  pangramma
Due  possibili modi di  creare un  
programma in  Python
Interattivo
Scriviamo ogni istruzione direttamente nell’interprete
Python  e  otteniamo immediatamente una risposta
Script
Inseriamo una sequenza di  istruzioni in  un  file  
utilizzando un  editor  di  testo e  chiediamo a  Python  di  
eseguire le  istruzioni nel file
Come  convenzione,  salviamo il file  con  l’estensione
“.py” per  indicare che contiene un  programma Python.
VARIABILI E  COSTANTI
Costanti e  variabili

Costanti:  numeri,  lettere e  


stringhe che non  cambiano
>>> print(123)
il loro valore 123
Stringhe costanti sono >>> print(98.6)
98.6
racchiuse tra apici semplici >>> print('Hello world')
(') Hello world
o  doppi (") >>> x = 125
>>> print(x)
Variabili:  corrispondono ad   125
aree di  memoria nel >>> x = ‘Ciao Mondo!’
>>> print(x)
calcolatore.  Possono Ciao Mondo!
cambiare il loro valore nel
tempo
Espressioni numeriche

>>> xx = 2 >>> jj = 23 Operator Operation


>>> xx = xx + 2 >>> kk = jj % 5
>>> print(xx) >>> print(kk) + Addition
4 3
>>> print(4 ** 3) -­ Subtraction
>>> yy = 440 * 12
>>> print(yy) 64
* Multiplication
5280
>>> zz = yy / 1000 / Division
>>> print(zz)
5.28 ** Power

% 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

Python  conosce il tipo di  


qualsiasi valore >>> eee = 'hello ' + 'there'
>>> eee = eee + 1
Alcune operazioni sono Traceback (most recent call last):
File "<stdin>", line 1, in
proibite per  alcuni valori <module>TypeError: Can't convert
È possibile chiedere a   'int' object to str implicitly
>>> type(eee)
Python  il tipo di  una <class'str'>
>>> type('hello')
variabile/valore tramite la   <class'str'>
funzione type() >>> type(1)
<class'int'>
>>>
Diversi tipi  numerici

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

La  divisione intera produce  un  risultato float


In  altri linguaggi di  programmazione invece il risultato è
un  intero
>>> print(10 / 2)
5.0
>>> print(9 / 2)
4.5
>>> print(99 / 100)
0.99
>>> print(10.0 / 2.0)
5.0
>>> print(99.0 / 100.0)
0.99
Input  dell’utente

Si  può chiedere a  Python  di  fermarsi e  leggere dati


dall’utente usando la  funzione input()
input()  restituisce una stringa
Programma
nam = input('Who are you? ')
print('Welcome', nam)

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

# This code transforms floor numbers from the


# European to the US convention
inp = input('Europe floor?')
usf = int(inp) + 1
print('US floor', usf)

#  indica l’inizio di  un  commento


Perchè usare i commenti?
Per  descrivere che cosa fa  una certa sequenza di  
istruzioni
Per  indicare l’autore del  codice,  la  data,  la  versione,  …
Per  escludere temporaneamente un’istruzione dal  
programma
Esercizio

Vogliamo calcolare il salario di  un  impiegato.  


Scrivi un  programma che chieda all’utente il
numero di  ore  di  lavoro e  la  paga oraria e  
calcoli il salario totale

Inserisci il numero di ore: 35


Inserisci la paga oraria: 2.75

Salario totale: 96.25


ANCORA SULLE ISTRUZIONI
CONDIZIONALI
Istruzioni condizionali

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

Gli operatori di  confronto Python Significato


danno come  risultato True  /   < Minore di
False <= Minore o  uguale a
Non  modificano il valore delle ==   Uguale a
variabili >= Maggiore  o  uguale a
> Maggiore  di
!= Non  uguale

RICORDA:    “=” è usato per  


l’assegnamento!
http://en.wikipedia.org/wiki/George_Boole
Indentazione

È il modo per  delimitare blocchi di  istruzioni

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

Riscrivi il programma per  il calcolo del  salario in  


modo da  attribuire all’impiegato un  salario orario
pari a  1.5  volte  la  paga oraria normale per  ogni
ora di  lavoro ulteriore rispetto al  minimo di  40  ore.

Inserisci il numero di ore: 45


Inserisci la paga oraria: 10

Salario totale: 475


475  =  40  *  10  +  5  *  15
Operatori logici

not A  -­>  vera quando A  è falsa  e  viceversa


A  and B  -­>  vera quando sia A  che B  sono vere,  falsa  
altrimenti
A  or B  -­>  vera quando A  o  B  sono vere,  falsa  quando
sia A  che B  sono false

inYear = input('insert a year ')


year = int(inYear)
if (year%400==0) or (year%4==0 and year%100!=0) :
print('it is bissextile')
else :
print('it is not bissextile')
ANCORA SUI  CICLI
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.
Definite  loop

Supponiamo di  avere un  insieme di  cose (una


stringa,  un  insieme di  numeri,  …)
Possiamo scrivere un  ciclo che esegue un  blocco di  
istruzioni per  ciascun elemento dell’insieme
Questo è chiamato “definite  loop”  perchè viene
eseguito un  numero esatto di  volte
Possiamo dire  che i definite  loop  iterano sui  membri
di  un  insieme
Il  costrutto da  utilizzare il Python  è il for
Un  semplice 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

Happy  New  Year:  Joseph


friends = ['Joseph', 'Glenn', 'Sally'] Happy  New  Year:  Glenn
for friend in friends : Happy  New  Year:  Sally
print('Happy New Year:', friend)
print(Fatto!')
Fatto!
Esercizio

Riscrivi l’esempio del  calcolo del  salario in  modo che esegua il


calcolo per  10  impiegati.  Per  ciascun impiegato acquisisci,  
come  prima,  il numero di  ore  di  lavoro e  il salario orario

Impiegato 1
Inserisci il numero di ore: 45
Inserisci la paga oraria: 10

Salario totale: 475

Impiegato 2
Inserisci il numero di ore: 32
Inserisci la paga oraria: 12

Salario totale: 384.0


Else  come  parte  dei cicli

Sia il while  che il for  possono terminare con  un  else


L’else è eseguito quando la  condizione del  ciclo
diventa falsa  o,  nei definite  loop,  quando non  ci  sono
altri elementi da  considerare nell’insieme di  valori su
cui  si itera
Else  al  lavoro

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

Per  x  ==  -­1


I  am  in  the  else  -­1
I  am  out  of  the  loop
Sommario

Introduzione alla Operatori


programmazione Input  dall’utente
Caratteristiche generali di   Commenti (#)
Python Istruzioni condizionali
Variabili e  costanti Istruzioni ripetute
Tipi
Conversioni tra tipi
Domande/esercizi utili per  il ripasso

Che cosa è un  programma?


Fornite due  esempi di  programmi che conoscete
Perchè è utile  scrivere programmi?
Com’è organizzato un  computer?
Che differenza c’è tra un  compilatore e  un  interprete?
Qual è la  differenza tra istruzioni sequenziali,  
condizionali e  loop?
Provate a  pensare a  che cosa è un  loop  infinito:  
sapreste costruirne uno in  Python?    
Domande/esercizi utili per  il ripasso
Scrivere un  programma che calcola il valore assoluto
di  un  numero
Scrivere il programma del  pangramma
Provare a  eseguirlo,  guardare qui  
https://it.wikipedia.org/wiki/Pangramma per  esempi di  
pangrammi
Scoprire che cosa fa  questa istruzione
a  =  [chr(ord('a')+i)  for  i in  range(26)]
Possiamo usarla nel programma del  pangramma?  
Come?
Cercare informazioni sull’ENIAC e  scrivere con  
parole  vostre,  in  poche righe,  di  che cosa si tratta
Cercare informazioni su Cloud  Computing  e  Big  data  
Acknowledgements  /  Contributions

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.    

Adaptation  and  extensions:  Elisabetta Di  Nitto,  Politecnico di  Milano


Politecnico
di Milano

Coding in  Python

10-­14  Giugno  2018

Lezione  2
STRINGS
Looking  Inside  Strings

We  can  get  at  any  single  


b a n a n a
character  in  a  string  using  an  
0 1 2 3 4 5
index  specified  in  square  
brackets >>>
>>>
fruit = 'banana'
letter = fruit[1]
The  index  value  must  be  an   >>> print(letter)
a
integer  and  starts  at  zero >>> x = 3
The  index  value  can  be  an   >>> w = fruit[x - 1]
>>> print(w)
expression  that  is  computed n
Looping  Through  Strings

Using  a  while  statement,  an  iteration  variable,  and  


the  len  function,  we  can  construct  a  loop  to  look  at  
each  of  the  letters  in  a  string  individually

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

A  definite  loop  using  a  for  statement  is  much  more  


elegant
The  iteration  variable  is  completely  taken  care  of  by  
the  for  loop

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

Write  a  program  that  decides  whether  a  word  is  a  


palindrome  
adda
ottetto
radar
Solution  1

word = input('Insert a word ')


i = 0
j = len(word)-1
while i<j/2 and word[i]==word[j]:
i = i+1
j = j-1
if i >= j/2:
print('the word is palindrome')
else :
print('the word is not palindrome')
Solution  2

word = input('Insert a word ')


if word == word[::-1]:
print('the word is palindrome')
else :
print('the word is not palindrome')
String  Concatenation

When  the    +    operator  is  applied  to  strings,  it  means  


“concatenation”

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

Python  has  a  number  of  


string  functions  which  are  
in  the  string  library
These  functions  are   >>> greet = 'Hello Bob'
already  built  into  every   >>> zap = greet.lower()
>>> print(zap)
string  -­ we  invoke  them  by  
hello bob
appending  the  function  to   >>> print(greet)
the  string  variable Hello Bob
>>> print('Hi There'.lower())
These  functions  do  not  
hi there
modify  the  original  string,   >>>
instead  they  return  a  new  
string  that  has  been  
altered
String  Library

>>> stuff = 'Hello world'


>>> type(stuff)
<class 'str'>
>>> dir(stuff)
['capitalize', 'casefold', 'center', 'count', 'encode',
'endswith', 'expandtabs', 'find', 'format', 'format_map',
'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit',
'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace',
'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip',
'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust',
'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines',
'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper',
'zfill']

https://docs.python.org/3/library/stdtypes.html#string-methods
String  Library
Searching  a  String

We  use  the  find()  function  to  


search  for  a  substring  within  
another  string b a n a n a
find()  finds  the  first  occurrence   0 1 2 3 4 5
of  the  substring
If  the  substring  is  not  found,   >>> fruit = 'banana'
>>> pos = fruit.find('na')
find()  returns  -­1 >>> print(pos)
Remember  that  string  position   2
>>> aa = fruit.find('z')
starts  at  zero >>> print(aa)
-1
Making  everything  UPPER  CASE

You  can  make  a  copy  of  a  


string  in  lower  case  or  upper  
case
Often  when  we  are  
>>> greet = 'Hello Bob'
searching  for  a  string  using   >>> nnn = greet.upper()
find()  we  first  convert  the   >>> print(nnn)
string  to  lower  case  so  we   HELLO BOB
can  search  a  string   >>> www = greet.lower()
regardless  of  case >>> print(www)
hello bob
>>>
Search  and  Replace

The  replace()  function  


is  like  a  “search  and  
replace” operation  in  a   >>> greet = 'Hello Bob'
word  processor >>> nstr = greet.replace('Bob','Jane')
>>> print(nstr)
It  replaces  all   Hello Jane
occurrences  of  the   >>> nstr = greet.replace('o','X')
>>> print(nstr)
search  string  with  the   HellX BXb
replacement  string >>>
Stripping  Whitespace

Sometimes  we  want  to  take  a  string  and  remove  


whitespace  at  the  beginning  and/or  end
lstrip()  and  rstrip()  remove  whitespace  at  the  left  or  
right
strip()  removes  both  beginning  and  ending  
whitespace
>>> greet = ' Hello Bob '
>>> greet.lstrip()
'Hello Bob '
>>> greet.rstrip()
' Hello Bob'
>>> greet.strip()
'Hello Bob'
>>>
Prefixes

>>> line = 'Please have a nice day'


>>> line.startswith('Please')
True
>>> line.startswith('p')
False
Parsing  and  extracting

21 31

From [email protected] Sat Jan 5 09:14:16 2008

>>> data = 'From [email protected] Sat Jan 5 09:14:16 2008'


>>> atpos = data.find('@')
>>> print(atpos)
21
>>> sppos = data.find(' ',atpos)
>>> print(sppos)
31
>>> host = data[atpos+1 : sppos]
>>> print(host)
uct.ac.za
LISTS
A  List  is  a  Kind  of  Collection

A  collection  allows  us  to  put  many  values  in  a  single  


“variable”
A  collection  is  nice  because  we  can  carry  all  many  
values  around  in  one  convenient  package.

friends = [ 'Joseph', 'Glenn', 'Sally' ]

carryon = [ 'socks', 'shirt', 'perfume' ]


List  Constants

List  constants  are  surrounded  by  square  brackets  


and  the  elements  in  the  list  are  separated  by  commas
A  list  element  can  be  any  Python  object  -­ even  
another  list
A  list  can  be  empty >>> print([1, 24, 76])
[1, 24, 76]
>>> print(['red', 'yellow', 'blue'])
['red', 'yellow', 'blue']
>>> print(['red', 24, 98.6])
['red', 24, 98.6]
>>> print([ 1, [5, 6], 7])
[1, [5, 6], 7]
>>> print([])
[]
A  use  of  lists  we  have  already  seen

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

>>> friends = [ 'Joseph', 'Glenn', 'Sally' ]


Joseph Glenn Sally >>> print(friends[1])
Glenn
0 1 2 >>>
How  Long  is  a  List?

>>> greet = 'Hello Bob'


The  len()  function  takes  a  list  as  
>>> print(len(greet))
a  parameter  and  returns  the  
9
number  of  elements  in  the  list
>>> x = [ 1, 2, 'joe', 99]
Actually  len()  tells  us  the   >>> print(len(x))
number  of  elements  of  any  set   4
or  sequence  (such  as  a  string...) >>>
Using  the  range  Function

The  range  function  


returns  a  list  of  numbers  
that  range  from  zero  to  
one  less  than  the  
parameter >>> print(range(4))
[0, 1, 2, 3]
We  can  construct  an   >>> friends = ['Joseph', 'Glenn',
'Sally']
index  loop  using  for  and   >>> print(len(friends))
3
an  integer  iterator >>> print(range(len(friends)))
[0, 1, 2]
>>>
Concatenating  Lists  Using  +

We  can  create  a  new  list  by  adding  two  existing  lists  


together

>>> 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  :

>>> t = [9, 41, 12, 3, 74, 15]


>>> t[1:3]
[41,12]
Remember:    the  second  number  
>>> t[:4]
[9, 41, 12, 3] is  “up  to  but  not  including”
>>> t[3:]
[3, 74, 15]
>>> t[:]
[9, 41, 12, 3, 74, 15]
>>> s = t[:]
>>> s
[9, 41, 12, 3, 74, 15]
List  Methods

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

We  can  create  an  empty  list  and  then  add  elements  


using  the  append  method
The  list  stays  in  order  and  new  elements  are  added  
at  the  end  of  the  list

>>> stuff = list()


>>> stuff.append('book')
>>> stuff.append(99)
>>> print(stuff)
['book', 99]
>>> stuff.append('cookie')
>>> print(stuff)
['book', 99, 'cookie']
Is  Something  in  a  List?

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

>>> some = [1, 9, 21, 10, 16]


>>> 9 in some
True
>>> 15 in some
False
>>> 20 not in some
True
>>>
Comprehensions:  basics
It  is  a  way  of  creating  a  new  list  from  an  existing  one.
Its  syntax  is  derived  from  a  construct  in  set  theory  
notation  that  applies  an  operation  to  each  item  in  a  
set [ expression for var in list ]
>>>  L  =  [1,2,3,4,5]
list comprehensions are introduced
>>>  res  =  [x  +  10  for  x  in  L] by square brackets
is  equivalent  to   …we are creating a 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  =  [chr(ord('a')+i)  for  i in  range(26)]


Equivalent  to
a=  []
for  i in  range(26)
a.append(chr(ord(‘a’)+i))

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

>>> lotto = [2, 14, 26, 41, 63]


>>> fruit = 'Banana' >>> print(lotto)
>>> fruit[0] = 'b' [2, 14, 26, 41, 63]
Traceback >>> lotto[2] = 28
TypeError: 'str' object does not >>> print(lotto)
support item assignment [2, 14, 28, 41, 63]
Python  types  and  immutability

From  https://medium.com/@meghamohan/mutable-­
and-­immutable-­side-­of-­python-­c2145cf72747
Built-­in  Functions  and  Lists

There  are  a  number  of  functions  built  into  Python  that  


take  lists  as  parameters

>>> nums = [3, 41, 12, 9, 74, 15]


>>> print(len(nums))
6
>>> print(max(nums))
74
>>> print(min(nums))
3
>>> print(sum(nums))
154
>>> print(sum(nums)/len(nums))
25.6
Best  Friends:  Strings  and  Lists

>>> abc = 'With three words' >>> print(stuff)


>>> stuff = abc.split() ['With', 'three', 'words']
>>> print(stuff) >>> for w in stuff :
['With', 'three', 'words'] ... print(w)
>>> print(len(stuff)) ...
3 With
>>> print(stuff[0]) Three
With Words
>>>

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

>>> line = 'A lot of spaces'


>>> etc = line.split()
>>> print(etc)
['A', 'lot', 'of', 'spaces'] ● When  you  do  not  specify  a  
>>>
>>> line = 'first;second;third' delimiter,  multiple  spaces  are  
>>> thing = line.split()
>>> print(thing) treated  like  one  delimiter
['first;second;third']
>>> print(len(thing))
1
● You  can  specify  what  delimiter  
>>> thing = line.split(';')
>>> print(thing) character  to  use  in  the  splitting
['first', 'second', 'third']
>>> print(len(thing))
3
>>>
The  Double  Split  Pattern

Sometimes  we  split  a  line  one  way,  and  then  grab  


one  of  the  pieces  of  the  line  and  split  that  piece  again

From [email protected] Sat Jan 5 09:14:16 2008

words = line.split()
email = words[1]
The  Double  Split  Pattern

From [email protected] Sat Jan 5 09:14:16 2008

words = line.split()
email = words[1] [email protected]
print email
The  Double  Split  Pattern

From [email protected] Sat Jan 5 09:14:16 2008

words = line.split()
email = words[1] [email protected]
pieces = email.split('@') ['stephen.marquard', 'uct.ac.za']
print pieces[1]
The  Double  Split  Pattern

From [email protected] Sat Jan 5 09:14:16 2008

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

Central Main Peripheral Peripheral


Processing Memory Interface I1 Interface In
Unit Secondary
Memory

Files  are  here


File  Processing

A  text  file  can  be  thought  of  as  a  sequence  of  lines

From [email protected] Sat Jan 5 09:14:16 2008


Return-Path: <[email protected]>
Date: Sat, 5 Jan 2008 09:12:18 -0500
To: [email protected]
From: [email protected]
Subject: [sakai] svn commit: r39772 - content/branches/

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’, ‘w’)


>>> myFile.write(‘hello text file\n’)
16
>>> myFile.write(‘goodbye text file\n’)
18
>>> myFile.close()

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

Scrivere un  programma che legge un  testo da  file  e  


conta il numero di  articoli determinativi e  
indeterminativi nel file
Impiccato (Hangman)

Sviluppare un  programma per  il gioco dell’impiccato

http://www.hangman.no
Altri esercizi

Studiare la  documentazione sulle operazioni per  le  


stringhe e  le  liste e  provare a  utilizzare le  operazioni
che interessano di  più
Cercare su wikipedia il significato di  file  csv
Scrivere un  programma che,  dato un  file  strutturato
secondo  il formato csv  e  contenente nome,  cognome
e  voto di  un  insieme di  studenti,  calcola la  media  dei
voti
Acknowledgements  /  Contributions

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

Potrebbero piacerti anche