Coding in Python 11- 15 Giugno 2018 - Politecnico di Milano - Polimi
←
→
Trascrizione del contenuto della pagina
Se il tuo browser non visualizza correttamente la pagina, ti preghiamo di leggere il contenuto della pagina quaggiù
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
Elisabetta Di Nitto (lezione 1, 2 e 5) Gianmarco Loliva (mattina e
Via Golgi, 42 pomeriggio)
email elisabetta.dinitto@polimi.it email
gianmarco.loliva@mail.polimi.it
tel: 02-2399-3663
http://dinitto.faculty.polimi.it
Michele Lambertucci (pomeriggio)
email
Alessandro Campi (lezione 3 e 4) michele.lambertucci@mail.polimi.it
Via Ponzio 34/5
Aspetti logistici e amministrativi
email alessando.campi@polimi.it
Laura Brambilla
tel: 02-2399-3644
Via Ponzio 34/5
email laura.brambilla@polimi.it
tel: 02-2399-3427Organizzazione del laboratorio
Mattina dalle 9.00 alle 12.00
Lezioni
Pomeriggio dalle 13.00 alle 16.00
Studio autonomo e svolgimento di esercizi
Aula G.0.2Materiale
Libri online in Inglese
www.py4e.com
http://docs.python-guide.org/en/latest/ (argomenti più
avanzati)
Slide del corsoUn 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
7Utenti, 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 alleatiSoftware, 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 umani
https://www.youtube.com/watch?v=SWLl5ejQY5cProgrammi 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
UnitRappresentazione 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”: 00110000Esempio 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 ZLinguaggio 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 calcolatoreCome fa la nostra macchina ad eseguire
programmi in linguaggio di alto livello?
Seconda possibilità: non operiamo una
trasformazione a priori prima dell’esecuzione, usiamo
i servizi di un interprete
Istruzione in
Programma Interprete linguaggio
in Python
macchina
L’interprete legge e traduce al volo durante
l’esecuzioneAmbienti 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 interpretePYTHON 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 Useremo questo
30Elementi 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 raiseVariabili
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
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
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
FunzioneProgram Steps or Program Flow Like a recipe or installation instructions, a program is a sequence of steps to be done in order. Some steps are conditional - they may be skipped. Sometimes a step or group of steps is to be repeated. Sometimes we store a set of steps to be used over and over as needed several places throughout the program (these are functions).
Sequential Steps
x = 2 Program:
Output:
print(x) x = 2
print(x) 2
x = x + 2 x = x + 2 4
print(x)
print(x)
When a program is running, it flows from one step to the next. As
programmers, we set up “paths” for the program to follow.Conditional Steps
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')Repeated Steps
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!
Loops (repeated steps) have iteration variables that
print('Blastoff')
change each time through a loop.Classifying the instructions of our first
example…
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: Sequential
print('the string is not a pangram')
else: Repeated
print('the string is a pangram') ConditionalWords, sentences and paragraphs
text = input('Write a sentence: ') A short Python “Story”
about how identifying
Alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', pangrams
'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r',
's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
A word used to read
notAPangram = False data from a user
for letter in Alphabet: A sentence about
if letter not in text: considering all
notAPangram = True
alphabet letters
if notAPangram:
print('the string is not a pangram') A paragraph about
else: informing the usage of
print('the string is a pangram')
the program outcomeInteractive versus Script
Interactive
We type directly to Python one line at a time and it
responds
Script
We enter a sequence of statements (lines) into a file
using a text editor and tell Python to execute the
statements in the file
As a convention, we add “.py” as the suffix on the end
of these files to indicate they contain Python.VARIABLES AND CONSTANTS
Constants
Fixed values such as numbers, letters, and strings,
are called “constants” because their value does not
change
Numeric constants are as you expect
String constants use single quotes (')
or double quotes (")
>>> print(123)
123
>>> print(98.6)
98.6
>>> print('Hello world')
Hello worldNumeric Expressions
>>> 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 4 R 3 / Division
>>> print(zz) 5 23
5.28 20 ** Power
3 % RemainderWhat Does “Type” Mean?
In Python variables,
literals, and constants have
a “type”
Python knows the
difference between an >>> ddd = 1 + 4
>>> print(ddd)
integer number and a 5
string >>> eee = 'hello ' + 'there'
>>> print(eee)
For example “+” means hello there
“addition” if something is a
number and “concatenate”
if something is a string concatenate = put togetherType Matters
Python knows what
“type” everything is >>> eee = 'hello ' + 'there'
>>> eee = eee + 1
Some operations are Traceback (most recent call last):
File "", line 1, in
prohibited TypeError: Can't convert
You cannot “add 1” to a 'int' object to str implicitly
>>> type(eee)
string
>>> type('hello')
We can ask Python what
type something is by >>> type(1)
using the type() function >>>Several Types of Numbers
>>> xx = 1
Numbers have two main types >>> type (xx)
Integers are whole numbers:
-14, -2, 0, 1, 100, 401233 >>> temp = 98.6
>>> type(temp)
Floating Point Numbers have
decimal parts: >>> type(1)
-2.5 , 0.0, 98.6, 14.0
>>> type(1.0)
>>>Integer Division
Integer division produces a floating point result
>>> 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.99User Input
We can instruct Python to pause and read data from
the user using the input() function
The input() function returns a string
nam = input('Who are you? ')
print('Welcome', nam)
Who are you? Chuck
Welcome ChuckConverting User Input
If we want to read a
number from the user,
we must convert it from
inp = input('Europe floor?')
a string to a number usf = int(inp) + 1
using a type conversion print('US floor', usf)
function
Later we will deal with
Europe floor? 0
bad input data
US floor 1Comments in Python
Anything after a # is ignored by Python but very
useful for programmers and those willing to
understand a piece of code
Why comment?
Describe what is going to happen in a sequence of
code
Document who wrote the code or other ancillary
information
Turn off a line of code - perhaps temporarily
# This code transforms floor numbers from the
# European to the US convention
inp = input('Europe floor?')
usf = int(inp) + 1
print('US floor', usf)Exercise
Write a program to prompt the user for hours
and rate per hour to compute gross pay.
Enter Hours: 35
Enter Rate: 2.75
Pay: 96.25MORE ON CONDITIONAL STEPS
Conditional Steps
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')Comparison Operators
Boolean expressions using Python Meaning
comparison operators evaluate < Less than
to True / False or Yes / No = Greater than or Equal to
the variables > Greater than
!= Not equal
Remember: “=” is used for assignment.
http://en.wikipedia.org/wiki/George_BooleIndentation
It is the way to delimit a block of instructions
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')Indentation Increase indent indent after an if statement or for statement (after : ) Maintain indent to indicate the scope of the block (which lines are affected by the if/for) Reduce indent back to the level of the if statement or for statement to indicate the end of the block Blank lines are ignored - they do not affect indentation Comments on a line by themselves are ignored with regard to indentation
Two-way Decisions with 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')Multi-way
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')Exercise
Rewrite your pay computation to give the
employee 1.5 times the hourly rate for hours
worked above 40 hours.
Enter Hours: 45
Enter Rate: 10
Pay: 475.0
475 = 40 * 10 + 5 * 15Logical operators
not A -> true when A is false and vice versa
A and B -> true when both A and B are true, false
otherwise
A or B -> true when either A or B are true, false when
both A and B are 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')MORE ON REPEATED STEPS (LOOPS)
Repeated Steps
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!
Loops (repeated steps) have iteration variables that
print('Blastoff')
change each time through a loop.Definite Loops When we have a finite set of things We can write a loop that executes a block for each of the items in the set using the Python for construct These are called “definite loops” because they execute an exact number of times We say that “definite loops iterate through the members of a set”
A Simple Definite Loop
5
for i in [5, 4, 3, 2, 1] :
print(i)
4
print('Blastoff!') 3
2
1
Blastoff!A Definite Loop with Strings
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('Done!')
Done!Exercise Rewrite your pay computation to compute the salary of 10 employees. For each employee, acquire the hours and the rate as before Employee 1 Enter Hours: 45 Enter Rate: 10 Pay: 475.0 Employee 2 Enter Hours: 32 Enter Rate: 12 Pay: 384.0
Else as part of loops Both while and for can terminate with an else statement The else is executed when the condition in the loop becomes false
Else at work
If 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')
If x == -1
I am in the else -1
I am out of the loopSummary Introduction to Conversion between programming types Python overview User input Variables and constants Comments (#) Types Conditional steps Operators Repeated steps
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
Puoi anche leggere