Fondamenti di Programmazione

Andrea Sterbini

lezione 3 - 10 ottobre 2022

Ancora a proposito di stringhe¶

Le stringhe str sono piu complesse di int e float.
E' possibile pensarle codificate in memoria come vettori (sequenze di elementi uguali).

In [1]:
nome = 'andrea sterbini'

carattere | a | n | d | r | e | a | | s | t | e | r | b | i | n | i | -- | -- | --| --| --| --| --| --| --| --| --| --| --| --| --| --| indice | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10| 11| 12| 13| 14|

  1. Si ottiene la lunghezza della sequenza di caratteri con len(nome)
  1. E' possibile anche:
    • indicizzare la stringa, ossia accedere in maniera secca (random access) a ciascun carattere
    • l'indicizzazione avviene come se fosse un vettore
    • per vedere il carattere quinto, non importa che chieda prima secondo, terzo e quarto. Accedo diretto al quinto nome[4]
  1. Molto importante!
    in informatica si inizia a contare da 0
    • nome[0] è il primo elemento

carattere | a | n | d | r | e | a | | s | t | e | r | b | i | n | i | -- | -- | --| --| --| --| --| --| --| --| --| --| --| --| --| --| indice | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10| 11| 12| 13| 14|

In [2]:
nome[0]
Out[2]:
'a'
In [3]:
nome[100]  #attenzione il mio nome e cognome non arriva a 100 caratteri
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
/tmp/ipykernel_9389/2238065423.py in <cell line: 1>()
----> 1 nome[100]  #attenzione il mio nome e cognome non arriva a 100 caratteri

IndexError: string index out of range
In [4]:
len(nome) #infatti i caratteri sono 15
Out[4]:
15
In [5]:
# ok accediamo all quindicesimo
nome[15]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
/tmp/ipykernel_9389/3779975648.py in <cell line: 2>()
      1 # ok accediamo all quindicesimo
----> 2 nome[15]

IndexError: string index out of range

😨¶

carattere | a | n | d | r | e | a | | s | t | e | r | b | i | n | i | -- | -- | --| --| --| --| --| --| --| --| --| --| --| --| --| --| indice | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10| 11| 12| 13| 14|

In [6]:
start = nome[0]                 # accedo al primo elemento, lo metto dentro start
end = nome[len(nome)-1]         # calcolo la lunghezza della stringa. 
                                # ultimo elemento è in posizione luneghezza-1. Ci accedo
                                # lo metto dentro end
print(start)  #stampa la prima lettera
print(end)    #stampa l'ultima lettera
a
i
In [7]:
# Posso invece contare dalla fine 
ultimo = nome[-1]               
penultimo = nome[-2]            
print(ultimo)
print(penultimo)
i
n
In [8]:
# possiamo anche "affettare" la stringa 
# per estrarre il mio nome (slicing)
nome[0:6] # da notare MOLTO IMPORTANTE
          # 0 e' compreso, 6 escluso
Out[8]:
'andrea'

car.| a | n | d | r | e | a | ----|---|---|---|---|---|---| idx | 0 | 1 | 2 | 3 | 4 | 5 |

Assumiamo di volere estrarre drea
da andrea sterbini.

  • Come facciamo?
  • Ricordiamoci che il carattere spazio nel mezzo e' un carattere (lo spazio si codifica nel computer)

carattere | a | n | d | r | e | a | | s | t | e | r | b | i | n | i | -- | -- | --| --| --| --| --| --| --| --| --| --| --| --| --| --| indice | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10| 11| 12| 13| 14|

  • Possiamo fare slicing con l'operatore : da 2 a 6 ossia [2:6] (prendi la fetta che va dall'indice 2 al 6 escluso)
  • Ricordatevi gli indici di slicing in python sono sempre $[\text{ start},\text{end })$
  • start incluso, end ESCLUSO
In [9]:
sub_name = nome[2:6]
print(sub_name)
drea

E se non sappiamo dove inizia drea, che facciamo?

  • Sappiamo che dobbiamo cercare drea
  • drea è lungo 4 caratteri, ma possiamo usare il metodo len() per calcolarsi la lunghezza della stringa, cosi funzionerà con tutte le stringhe, non solo con drea.
  • Come facciamo a trovare l'indice di inizio di drea dentro nome?

Se ci fate caso ci stiamo piano piano approcciando al problem solving

In [10]:
help(str) # conviene leggersi le funzionalita' del tipo str
Help on class str in module builtins:

class str(object)
 |  str(object='') -> str
 |  str(bytes_or_buffer[, encoding[, errors]]) -> str
 |  
 |  Create a new string object from the given object. If encoding or
 |  errors is specified, then the object must expose a data buffer
 |  that will be decoded using the given encoding and error handler.
 |  Otherwise, returns the result of object.__str__() (if defined)
 |  or repr(object).
 |  encoding defaults to sys.getdefaultencoding().
 |  errors defaults to 'strict'.
 |  
 |  Methods defined here:
 |  
 |  __add__(self, value, /)
 |      Return self+value.
 |  
 |  __contains__(self, key, /)
 |      Return key in self.
 |  
 |  __eq__(self, value, /)
 |      Return self==value.
 |  
 |  __format__(self, format_spec, /)
 |      Return a formatted version of the string as described by format_spec.
 |  
 |  __ge__(self, value, /)
 |      Return self>=value.
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __getitem__(self, key, /)
 |      Return self[key].
 |  
 |  __getnewargs__(...)
 |  
 |  __gt__(self, value, /)
 |      Return self>value.
 |  
 |  __hash__(self, /)
 |      Return hash(self).
 |  
 |  __iter__(self, /)
 |      Implement iter(self).
 |  
 |  __le__(self, value, /)
 |      Return self<=value.
 |  
 |  __len__(self, /)
 |      Return len(self).
 |  
 |  __lt__(self, value, /)
 |      Return self<value.
 |  
 |  __mod__(self, value, /)
 |      Return self%value.
 |  
 |  __mul__(self, value, /)
 |      Return self*value.
 |  
 |  __ne__(self, value, /)
 |      Return self!=value.
 |  
 |  __repr__(self, /)
 |      Return repr(self).
 |  
 |  __rmod__(self, value, /)
 |      Return value%self.
 |  
 |  __rmul__(self, value, /)
 |      Return value*self.
 |  
 |  __sizeof__(self, /)
 |      Return the size of the string in memory, in bytes.
 |  
 |  __str__(self, /)
 |      Return str(self).
 |  
 |  capitalize(self, /)
 |      Return a capitalized version of the string.
 |      
 |      More specifically, make the first character have upper case and the rest lower
 |      case.
 |  
 |  casefold(self, /)
 |      Return a version of the string suitable for caseless comparisons.
 |  
 |  center(self, width, fillchar=' ', /)
 |      Return a centered string of length width.
 |      
 |      Padding is done using the specified fill character (default is a space).
 |  
 |  count(...)
 |      S.count(sub[, start[, end]]) -> int
 |      
 |      Return the number of non-overlapping occurrences of substring sub in
 |      string S[start:end].  Optional arguments start and end are
 |      interpreted as in slice notation.
 |  
 |  encode(self, /, encoding='utf-8', errors='strict')
 |      Encode the string using the codec registered for encoding.
 |      
 |      encoding
 |        The encoding in which to encode the string.
 |      errors
 |        The error handling scheme to use for encoding errors.
 |        The default is 'strict' meaning that encoding errors raise a
 |        UnicodeEncodeError.  Other possible values are 'ignore', 'replace' and
 |        'xmlcharrefreplace' as well as any other name registered with
 |        codecs.register_error that can handle UnicodeEncodeErrors.
 |  
 |  endswith(...)
 |      S.endswith(suffix[, start[, end]]) -> bool
 |      
 |      Return True if S ends with the specified suffix, False otherwise.
 |      With optional start, test S beginning at that position.
 |      With optional end, stop comparing S at that position.
 |      suffix can also be a tuple of strings to try.
 |  
 |  expandtabs(self, /, tabsize=8)
 |      Return a copy where all tab characters are expanded using spaces.
 |      
 |      If tabsize is not given, a tab size of 8 characters is assumed.
 |  
 |  find(...)
 |      S.find(sub[, start[, end]]) -> int
 |      
 |      Return the lowest index in S where substring sub is found,
 |      such that sub is contained within S[start:end].  Optional
 |      arguments start and end are interpreted as in slice notation.
 |      
 |      Return -1 on failure.
 |  
 |  format(...)
 |      S.format(*args, **kwargs) -> str
 |      
 |      Return a formatted version of S, using substitutions from args and kwargs.
 |      The substitutions are identified by braces ('{' and '}').
 |  
 |  format_map(...)
 |      S.format_map(mapping) -> str
 |      
 |      Return a formatted version of S, using substitutions from mapping.
 |      The substitutions are identified by braces ('{' and '}').
 |  
 |  index(...)
 |      S.index(sub[, start[, end]]) -> int
 |      
 |      Return the lowest index in S where substring sub is found,
 |      such that sub is contained within S[start:end].  Optional
 |      arguments start and end are interpreted as in slice notation.
 |      
 |      Raises ValueError when the substring is not found.
 |  
 |  isalnum(self, /)
 |      Return True if the string is an alpha-numeric string, False otherwise.
 |      
 |      A string is alpha-numeric if all characters in the string are alpha-numeric and
 |      there is at least one character in the string.
 |  
 |  isalpha(self, /)
 |      Return True if the string is an alphabetic string, False otherwise.
 |      
 |      A string is alphabetic if all characters in the string are alphabetic and there
 |      is at least one character in the string.
 |  
 |  isascii(self, /)
 |      Return True if all characters in the string are ASCII, False otherwise.
 |      
 |      ASCII characters have code points in the range U+0000-U+007F.
 |      Empty string is ASCII too.
 |  
 |  isdecimal(self, /)
 |      Return True if the string is a decimal string, False otherwise.
 |      
 |      A string is a decimal string if all characters in the string are decimal and
 |      there is at least one character in the string.
 |  
 |  isdigit(self, /)
 |      Return True if the string is a digit string, False otherwise.
 |      
 |      A string is a digit string if all characters in the string are digits and there
 |      is at least one character in the string.
 |  
 |  isidentifier(self, /)
 |      Return True if the string is a valid Python identifier, False otherwise.
 |      
 |      Call keyword.iskeyword(s) to test whether string s is a reserved identifier,
 |      such as "def" or "class".
 |  
 |  islower(self, /)
 |      Return True if the string is a lowercase string, False otherwise.
 |      
 |      A string is lowercase if all cased characters in the string are lowercase and
 |      there is at least one cased character in the string.
 |  
 |  isnumeric(self, /)
 |      Return True if the string is a numeric string, False otherwise.
 |      
 |      A string is numeric if all characters in the string are numeric and there is at
 |      least one character in the string.
 |  
 |  isprintable(self, /)
 |      Return True if the string is printable, False otherwise.
 |      
 |      A string is printable if all of its characters are considered printable in
 |      repr() or if it is empty.
 |  
 |  isspace(self, /)
 |      Return True if the string is a whitespace string, False otherwise.
 |      
 |      A string is whitespace if all characters in the string are whitespace and there
 |      is at least one character in the string.
 |  
 |  istitle(self, /)
 |      Return True if the string is a title-cased string, False otherwise.
 |      
 |      In a title-cased string, upper- and title-case characters may only
 |      follow uncased characters and lowercase characters only cased ones.
 |  
 |  isupper(self, /)
 |      Return True if the string is an uppercase string, False otherwise.
 |      
 |      A string is uppercase if all cased characters in the string are uppercase and
 |      there is at least one cased character in the string.
 |  
 |  join(self, iterable, /)
 |      Concatenate any number of strings.
 |      
 |      The string whose method is called is inserted in between each given string.
 |      The result is returned as a new string.
 |      
 |      Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
 |  
 |  ljust(self, width, fillchar=' ', /)
 |      Return a left-justified string of length width.
 |      
 |      Padding is done using the specified fill character (default is a space).
 |  
 |  lower(self, /)
 |      Return a copy of the string converted to lowercase.
 |  
 |  lstrip(self, chars=None, /)
 |      Return a copy of the string with leading whitespace removed.
 |      
 |      If chars is given and not None, remove characters in chars instead.
 |  
 |  partition(self, sep, /)
 |      Partition the string into three parts using the given separator.
 |      
 |      This will search for the separator in the string.  If the separator is found,
 |      returns a 3-tuple containing the part before the separator, the separator
 |      itself, and the part after it.
 |      
 |      If the separator is not found, returns a 3-tuple containing the original string
 |      and two empty strings.
 |  
 |  removeprefix(self, prefix, /)
 |      Return a str with the given prefix string removed if present.
 |      
 |      If the string starts with the prefix string, return string[len(prefix):].
 |      Otherwise, return a copy of the original string.
 |  
 |  removesuffix(self, suffix, /)
 |      Return a str with the given suffix string removed if present.
 |      
 |      If the string ends with the suffix string and that suffix is not empty,
 |      return string[:-len(suffix)]. Otherwise, return a copy of the original
 |      string.
 |  
 |  replace(self, old, new, count=-1, /)
 |      Return a copy with all occurrences of substring old replaced by new.
 |      
 |        count
 |          Maximum number of occurrences to replace.
 |          -1 (the default value) means replace all occurrences.
 |      
 |      If the optional argument count is given, only the first count occurrences are
 |      replaced.
 |  
 |  rfind(...)
 |      S.rfind(sub[, start[, end]]) -> int
 |      
 |      Return the highest index in S where substring sub is found,
 |      such that sub is contained within S[start:end].  Optional
 |      arguments start and end are interpreted as in slice notation.
 |      
 |      Return -1 on failure.
 |  
 |  rindex(...)
 |      S.rindex(sub[, start[, end]]) -> int
 |      
 |      Return the highest index in S where substring sub is found,
 |      such that sub is contained within S[start:end].  Optional
 |      arguments start and end are interpreted as in slice notation.
 |      
 |      Raises ValueError when the substring is not found.
 |  
 |  rjust(self, width, fillchar=' ', /)
 |      Return a right-justified string of length width.
 |      
 |      Padding is done using the specified fill character (default is a space).
 |  
 |  rpartition(self, sep, /)
 |      Partition the string into three parts using the given separator.
 |      
 |      This will search for the separator in the string, starting at the end. If
 |      the separator is found, returns a 3-tuple containing the part before the
 |      separator, the separator itself, and the part after it.
 |      
 |      If the separator is not found, returns a 3-tuple containing two empty strings
 |      and the original string.
 |  
 |  rsplit(self, /, sep=None, maxsplit=-1)
 |      Return a list of the substrings in the string, using sep as the separator string.
 |      
 |        sep
 |          The separator used to split the string.
 |      
 |          When set to None (the default value), will split on any whitespace
 |          character (including \\n \\r \\t \\f and spaces) and will discard
 |          empty strings from the result.
 |        maxsplit
 |          Maximum number of splits (starting from the left).
 |          -1 (the default value) means no limit.
 |      
 |      Splitting starts at the end of the string and works to the front.
 |  
 |  rstrip(self, chars=None, /)
 |      Return a copy of the string with trailing whitespace removed.
 |      
 |      If chars is given and not None, remove characters in chars instead.
 |  
 |  split(self, /, sep=None, maxsplit=-1)
 |      Return a list of the substrings in the string, using sep as the separator string.
 |      
 |        sep
 |          The separator used to split the string.
 |      
 |          When set to None (the default value), will split on any whitespace
 |          character (including \\n \\r \\t \\f and spaces) and will discard
 |          empty strings from the result.
 |        maxsplit
 |          Maximum number of splits (starting from the left).
 |          -1 (the default value) means no limit.
 |      
 |      Note, str.split() is mainly useful for data that has been intentionally
 |      delimited.  With natural text that includes punctuation, consider using
 |      the regular expression module.
 |  
 |  splitlines(self, /, keepends=False)
 |      Return a list of the lines in the string, breaking at line boundaries.
 |      
 |      Line breaks are not included in the resulting list unless keepends is given and
 |      true.
 |  
 |  startswith(...)
 |      S.startswith(prefix[, start[, end]]) -> bool
 |      
 |      Return True if S starts with the specified prefix, False otherwise.
 |      With optional start, test S beginning at that position.
 |      With optional end, stop comparing S at that position.
 |      prefix can also be a tuple of strings to try.
 |  
 |  strip(self, chars=None, /)
 |      Return a copy of the string with leading and trailing whitespace removed.
 |      
 |      If chars is given and not None, remove characters in chars instead.
 |  
 |  swapcase(self, /)
 |      Convert uppercase characters to lowercase and lowercase characters to uppercase.
 |  
 |  title(self, /)
 |      Return a version of the string where each word is titlecased.
 |      
 |      More specifically, words start with uppercased characters and all remaining
 |      cased characters have lower case.
 |  
 |  translate(self, table, /)
 |      Replace each character in the string using the given translation table.
 |      
 |        table
 |          Translation table, which must be a mapping of Unicode ordinals to
 |          Unicode ordinals, strings, or None.
 |      
 |      The table must implement lookup/indexing via __getitem__, for instance a
 |      dictionary or list.  If this operation raises LookupError, the character is
 |      left untouched.  Characters mapped to None are deleted.
 |  
 |  upper(self, /)
 |      Return a copy of the string converted to uppercase.
 |  
 |  zfill(self, width, /)
 |      Pad a numeric string with zeros on the left, to fill a field of the given width.
 |      
 |      The string is never truncated.
 |  
 |  ----------------------------------------------------------------------
 |  Static methods defined here:
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.
 |  
 |  maketrans(...)
 |      Return a translation table usable for str.translate().
 |      
 |      If there is only one argument, it must be a dictionary mapping Unicode
 |      ordinals (integers) or characters to Unicode ordinals, strings or None.
 |      Character keys will be then converted to ordinals.
 |      If there are two arguments, they must be strings of equal length, and
 |      in the resulting dictionary, each character in x will be mapped to the
 |      character at the same position in y. If there is a third argument, it
 |      must be a string, whose characters will be mapped to None in the result.

 |  index(...)
 |      S.index(sub[, start[, end]]) -> int
 |      
 |      Return the lowest index in S where substring sub is found,
 |      such that sub is contained within S[start:end].  Optional
 |      arguments start and end are interpreted as in slice notation.
 |      
 |      Raises ValueError when the substring is not found.

S.index(sottostringa) -> int

  1. prendo la stringa S ci applico la funzionalita' index che prende sottostringa come argomento
  2. Rende un intero -> int che indica la posizione trovata (oppure -1 se non c'è)
  3. Questa e' documentazione non codice
In [13]:
# quindi possiamo fare
# nome vale 'andrea sterbini '
start = nome.index('drea')
start
Out[13]:
False
In [14]:
nome[start:start+len('drea')] # [2,2+4) 
Out[14]:
'drea'

d | r | e | a | ---- | -- | -- | -- | 2 | 3 | 4 | 5 |

In [15]:
# mettendo tutto insieme 
query = 'drea'                    # input dell'algoritmo
start = nome.index(query)         # trovo il primo indice che contiene il contenut di QUERY 
                                  # sulla contenuto di NOME
end = start + len(query)          # mi precalcolo indice di fine stringa
sub_name = nome[start:end]        # faccio slicing della stringa
print(sub_name,start,end,nome)    # stampo cosa ho trovato e dove, a partire da cosa
drea 2 6 andrea sterbini

d | r | e | a | ---- | -- | -- | -- | 2 | 3 | 4 | 5 |

Di più su slicing¶

  • E' possibile anche non mettere il valore di start e end
  • E' possibile andare al contrario
  • E' possibile saltare ogni K elementi
In [16]:
nome[1:] # tutti i caratteri DOPO il 
         # primo (0 escluso, 1 compreso)
         # 0 | 1----------------- 
Out[16]:
'ndrea sterbini'
In [17]:
nome[:2] # tutti i caratteri PRIMA
         # del indice 2 escluso
         # quindi solo carattere 0-th
         # --0--1--| 2 3 4 5 6 7...
Out[17]:
'an'
In [18]:
nome[-1]  # al contrario di molti linguaggio a basso livello 
          # qui gli indici possono essere negativi
          # il meno inverte la sequenza di lettura
          # sto prendendo da 'andrea sterbini' <--- questa i finale
Out[18]:
'i'
  • Questa complessità è molto utile e efficace ma ovviamente va saputa gestire
  • Molto facile ingarbugarsi su slicing complessi perchè notazione è macchinosa (imho)
In [19]:
nome = 'Python'
vuoto = nome[4:3] # ovviamente se start >= end, abbiamo stringa vuota
type(vuoto),vuoto
Out[19]:
(str, '')
In [20]:
nome = 'Python'
vuoto = nome[-3:-4] # ovviamente se start >= end, abbiamo stringa vuota ''
type(vuoto),vuoto
Out[20]:
(str, '')
In [22]:
nome = 'Python'
nome[-4:-3] == nome[2:3], nome[2:3]
# questo funzione seleziona il carattere 't' (un singolo carattere e' una stringa)
Out[22]:
(True, 't')
In [23]:
nome = 'Python'
nome[-10:2], nome[3:100]
# se l'inizio è negativo e troppo grande si inizia dal primo carattere
# se la fine della slice è troppo grande si arriva all'ultimo
Out[23]:
('Py', 'hon')
In [24]:
nome[-1000]               
# MA ATTENZIONE: se invece indicizziamo il singolo carattere 
# non possiamo chiedere più di -(len(nome)-1)
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
/tmp/ipykernel_9389/137629210.py in <cell line: 1>()
----> 1 nome[-1000]
      2 # MA ATTENZIONE: se invece indicizziamo il singolo carattere
      3 # non possiamo chiedere più di -(len(nome)-1)

IndexError: string index out of range
In [25]:
# Prendiamo tutti i caratteri in posizione multipla di 3
# il terzo valore indica come incrementare l'indice
nome[::3]
Out[25]:
'Ph'
In [26]:
# prendiamoli in direzione opposta (incremento negativo)
nome[::-1]
Out[26]:
'nohtyP'

Momento Wooclap¶

quanto fa: 'ippopotamo'[2:-2:2] ?
e invece 'BabbuINO'.lower()[-1:-10:-3] ?

Screenshot%20from%202022-10-09%2020-28-21.png

In [27]:
# Risultati
'ippopotamo'[2:-2:2], 'BabbuINO'.lower()[-1:-10:-3]
Out[27]:
('ppt', 'oua')

Stringhe come Tipo Immutabile¶

  • I tipi mutabili e immutabili in python li vediamo meglio nelle prossime lezioni
  • Informalmente, un tipo immutabile vuol dire che una volta che e' stato creato NON può essere più modificato
  • Per chi viene dal C questa cosa non e' molto chiara perchè in C potete modificare direttamente le stringhe carattere per carattere
In [28]:
nome = 'Python'

assumiamo io voglia modificare la P di Python in minuscola python

In [29]:
# in C potrei fare
nome[0] = 'p'
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/tmp/ipykernel_9389/2897224970.py in <cell line: 2>()
      1 # in C potrei fare
----> 2 nome[0] = 'p'

TypeError: 'str' object does not support item assignment

In realta' non lo posso fare direttamente,
devo per forza creare un'altra stringa

In [30]:
A = nome.lower()     # trasformo tutto in minnuscole
A
Out[30]:
'python'
In [31]:
B = 'p'+nome[1:]     # oppure faccio cut/paste
B
Out[31]:
'python'
In [32]:
# con id(oggetto) posso capire se due cose sono lo stesso oggetto
id(A), id(B), id(A)==id(B)
# le due stringhe sono in posti diversi della memoria ?
Out[32]:
(139845825377904, 139845815550896, False)
In [33]:
 help(id)
Help on built-in function id in module builtins:

id(obj, /)
    Return the identity of an object.
    
    This is guaranteed to be unique among simultaneously existing objects.
    (CPython uses the object's memory address.)

String Literals¶

Se dobbiamo scrivere testi che contengono accapi ('\n') possiamo usare il triplo apice ''' oppure il triplo doppio apice """

In [36]:
print("""
Usage: thingy [OPTIONS]
     -h                        Display this usage message
     -H hostname               Hostname to connect to
""")
Usage: thingy [OPTIONS]
     -h                        Display this usage message
     -H hostname               Hostname to connect to

String interpolation¶

Possiamo costruire facilmente dei testi che contengono valori calcolati (ad es. presi da variabili)

  • precedendo la stringa con la lettera f (che sta per 'formatted')
  • inserendo i valori da interpolare tra parentesi graffe {espressione}
  • se vogliamo, indicando come visualizzare il dato interpolato (vedi documentazione)
In [37]:
# definiamo le parti da interpolare nel testo
nome      = 'Paolino'
cognome   = 'Paperino'
indirizzo = 'Via dei Peri 32'
data      = '29 febbraio'
orario    = '20:30'
mittente  = 'Gastone Paperone'
In [38]:
# e la lettera da spedire (che interpola semplici variabili)
lettera = f'''
Caro {nome} {cognome}
La invito al vernissage che si terrà a {indirizzo}
il giorno {data} alle ore {orario}
Cordialmente
{mittente}
'''
In [39]:
print(lettera)
Caro Paolino Paperino
La invito al vernissage che si terrà a Via dei Peri 32
il giorno 29 febbraio alle ore 20:30
Cordialmente
Gastone Paperone

Variabili e riferimenti¶

In [41]:
from graphviz import Digraph
# Create Digraph object
figura = Digraph()
figura.body.append('''
    graph [rankdir=LR]
    node [shape=rect]
    "namespace containing\n the variable (name)\nA" -> "RAM containing\n a reference to object" -> "RAM containing\n the object data"
''')
In [42]:
figura
## Ogni variabile è un nome contenuto in una tabella (namespace)
## che contiene un 'riferimento' all'oggetto in essa contenuto
Out[42]:
b'\n\n\n\n\nnamespace containing\n the variable (name)\nA\n\nnamespace containing\n the variable (name)\nA\n\n\n\nRAM containing\n a reference to object\n\nRAM containing\n a reference to object\n\n\n\nnamespace containing\n the variable (name)\nA->RAM containing\n a reference to object\n\n\n\n\n\nRAM containing\n the object data\n\nRAM containing\n the object data\n\n\n\nRAM containing\n a reference to object->RAM containing\n the object data\n\n\n\n\n\n'

Uguaglianza ed identità¶

Due oggetti possono essere abbastanza simili (se sono dello stesso tipo e contengono le stesse informazioni, sono interscambiabili)

Il confronto == torna True (uguaglianza dei contenuti)

Ma possono trovarsi in due aree di memoria diverse e quindi essere oggetti diversi (modificandone uno l'altro resta invariato)

Per distinguerli e sapere in qualche modo dove sono in memoria si usa la funzione id e per controllare se sono 'identici' si usa l'operatore is (identità)

In [43]:
# creiamo una stringa e copiamo la variabile A in B
A = 'Pippo e Pluto sono andati al mare con Minnie e Topolino'
B = A
# Se hanno lo stesso ID, di tratta dello stesso oggetto
print(id(A))
print(id(B))
A is B
139845815625952
139845815625952
Out[43]:
True
In [45]:
from graphviz import Digraph
def show_vars( *variabili ):
    grafo = Digraph()
    grafo.body.append(f'''
graph [rankdir=LR]
node  [shape=rect]''')
    for nome in variabili:
        valore = eval(nome)
        grafo.body.append(f'''
        {nome} -> "{id(valore)}"  -> "{valore}"
        ''')
    return grafo
In [46]:
show_vars( 'A', 'B' )
Out[46]:
b'\n\n\n\n\nA\n\nA\n\n\n\n139845815625952\n\n139845815625952\n\n\n\nA->139845815625952\n\n\n\n\n\nPippo e Pluto sono andati al mare con Minnie e Topolino\n\nPippo e Pluto sono andati al mare con Minnie e Topolino\n\n\n\n139845815625952->Pippo e Pluto sono andati al mare con Minnie e Topolino\n\n\n\n\n\n139845815625952->Pippo e Pluto sono andati al mare con Minnie e Topolino\n\n\n\n\n\nB\n\nB\n\n\n\nB->139845815625952\n\n\n\n\n\n'

Le variabili sono i nomi che diamo a luoghi nella memoria¶

e contengono un riferimento (indirizzo) dell'oggetto in memoria

  • possiamo modificare le info contenute in un oggetto 'riferito' da una variabile
  • oppure sostituire nella variabile il riferimento ad un altro oggetto
    L'operazione di assegnamento CAMBIA IL RIFERIMENTO contenuto nella variabile
In [47]:
# esempio: assegnamento che cambia il riferimento
A = 78
A_prima = A
A = 'paperino'
A_dopo  = A
print(id(A_prima))
print(id(A_dopo))
139846134631056
139845815881648
In [48]:
show_vars('A_prima')
Out[48]:
b'\n\n\n\n\nA_prima\n\nA_prima\n\n\n\n139846134631056\n\n139846134631056\n\n\n\nA_prima->139846134631056\n\n\n\n\n\n78\n\n78\n\n\n\n139846134631056->78\n\n\n\n\n\n'
In [49]:
show_vars('A_dopo')
Out[49]:
b'\n\n\n\n\nA_dopo\n\nA_dopo\n\n\n\n139845815881648\n\n139845815881648\n\n\n\nA_dopo->139845815881648\n\n\n\n\n\npaperino\n\npaperino\n\n\n\n139845815881648->paperino\n\n\n\n\n\n'
In [50]:
# Esempio di un contenitore: una lista di oggetti eterogenei
L = [1, 'due', 3.5]
# ne copio il riferimento in una seconda variabile
M = L
# sono proprio la stessa cosa
print(id(L),id(M), L is M)
139845815559808 139845815559808 True
In [132]:
show_vars('M', 'L') 
Out[132]:
b'\n\n\n\n\nM\n\nM\n\n\n\n140169610253312\n\n140169610253312\n\n\n\nM->140169610253312\n\n\n\n\n\n[1, \'due\', 3.5]\n\n[1, \'due\', 3.5]\n\n\n\n140169610253312->[1, \'due\', 3.5]\n\n\n\n\n\n140169610253312->[1, \'due\', 3.5]\n\n\n\n\n\nL\n\nL\n\n\n\nL->140169610253312\n\n\n\n\n\n'
In [51]:
# modifico il contenuto a posizione 1 (secondo elemento, si conta da 0)
L[1] = 42
# si tratta sempre dello stesso oggetto sia in L che in M
print('identici?', L is M, '\nuguali?', L == M)
# ed è stato modificato il secondo elemento
print(L, M)
identici? True 
uguali? True
[1, 42, 3.5] [1, 42, 3.5]
In [123]:
show_vars('M', 'L')
Out[123]:
b'\n\n\n\n\nM\n\nM\n\n\n\n140169611037056\n\n140169611037056\n\n\n\nM->140169611037056\n\n\n\n\n\n[1, 42, 3.5]\n\n[1, 42, 3.5]\n\n\n\n140169611037056->[1, 42, 3.5]\n\n\n\n\n\n140169611037056->[1, 42, 3.5]\n\n\n\n\n\nL\n\nL\n\n\n\nL->140169611037056\n\n\n\n\n\n'
In [52]:
# ma se creo una lista con gli stessi dati
L = [1, 42, 3.5]
print('identici?', L is M, '\nuguali?', L == M)
show_vars('M')
identici? False 
uguali? True
Out[52]:
b'\n\n\n\n\nM\n\nM\n\n\n\n139845815559808\n\n139845815559808\n\n\n\nM->139845815559808\n\n\n\n\n\n[1, 42, 3.5]\n\n[1, 42, 3.5]\n\n\n\n139845815559808->[1, 42, 3.5]\n\n\n\n\n\n'
In [137]:
show_vars('L')
Out[137]:
b'\n\n\n\n\nL\n\nL\n\n\n\n140169610263360\n\n140169610263360\n\n\n\nL->140169610263360\n\n\n\n\n\n[1, 42, 3.5]\n\n[1, 42, 3.5]\n\n\n\n140169610263360->[1, 42, 3.5]\n\n\n\n\n\n'

Tutti i dati in Python sono "oggetti"¶

  • un oggetto è un gruppo di informazioni coerenti (attributi)
    Es. cane: nome, altezza, razza, peso, colore, ...
    Es. str: lunghezza, sequenza di caratteri, ...
  • con tutte le operazioni che potete eseguire (metodi)
    Es. cane: abbaia, scodinzola, cammina, corre, salta
    Es. str: join, split, upper, lower, startswith, ...

int, str, bool, float, etc... sono oggetti
per scoprirne le caratteristiche usiamo help oppure ctrl-I in Spyder oppure . e l'autocompletamento

In [53]:
str              # testo
int              # interi                # abs, mod, %, //
float            # numeri con virgola
complex          # numeri complessi      # conjugate, imag, real, ...
bool             # booleani (True, False)# and, or, not

from fractions import Fraction  # frazioni intere
#help(Fraction)
f = Fraction(124,14)                     # denominator, numerator 
f
Out[53]:
Fraction(62, 7)

I metodi sono le operazioni che possiamo compiere su un oggetto¶

e che ne possono manipolare il contenuto o crearne di nuovi

Es. le operazioni su str

  • join, split, lower, upper, find, ...

Per eseguire un metodo di un oggetto¶

si usa la sintassi oggetto.nomedelmetodo(argomenti)

In [66]:
# Esempi
S = 'Paperino andò\t al, mare\n a nuotare'
# split (e varianti)
L = S.split()
# join
'|'.join(L)
S.lower()
# islower, isupper, isalpha, isnumeric
S.islower()
# upper, lower, title
S.upper()
# find
S.find('mare')
Out[66]:
19

NOTA: le stringhe sono IMMUTABILI, ogni volta che ci fate operazioni sopra ne create una nuova

NOTA: per rendere più efficiente l'uso della memoria¶

Python, invece che duplicarle, tiene copie uniche dei numeri piccoli e delle stringhe corte

In [67]:
B = 93
C = 92+1
print(id(B), id(C))
B is C
139846134631536 139846134631536
Out[67]:
True
In [70]:
# per le stringhe l'ottimizzazione è applicata alle 'parole' 
# che non contengono spazi (particolarmente importante nella 
# ottimizzazione del codice in memoria)
S1 = 'giovanni' * 50
S2 = 'giovanni' * 50
print(id(S1), id(S2))
S1 is S2
139845825296944 139845825296944
Out[70]:
True
In [72]:
# esempio di ottimizzazione dei piccoli numeri
esponente = 2
print((34**esponente) == ((30+4)**esponente), 'uguaglianza')
print((34**esponente) is ((30+4)**esponente), 'identità')
True uguaglianza
False identità

Modello dei dati di Python¶

DUCK typing: "se cammina come una papera e fa 'quack' come una papera, allora è una papera"¶

Nel modello dei dati del Python vogliamo che due oggetti siano intercambiabili quando 'si comportano allo stesso modo'

'si comportano allo stesso modo' == 'hanno gli stessi metodi'

(MA NOTATE: metodi con nomi uguali potrebbero avere realizzazioni interne diverse)

E' quindi possibile costruire nuovi tipi di oggetti che si comportano in modo simile ad altri

i numeri interi e i float sono un esempio (e anche i razionali e i complessi)

(vedremo in seguito come farlo)

NOTA: incapsulamento delle informazioni¶

gli attributi (informazioni interne) degli oggetti in Python NON sono protetti

In altri linguaggi compilati (Java, C++) è possibile 'nascondere' le informazioni interne e fare in modo che solo i metodi dell'oggetto le possano manipolare

In Python (interpretato) questo non è possibile (o è stato scelto così)

Ma si è stabilito che per convenzione

TUTTI GLI ATTRIBUTI E METODI CHE INIZIANO CON '_' SONO PRIVATI

e non vanno letti o modificati o usati direttamente

(chi li ha inventati potrebbe benissimo modificarli in future versioni del programma)

quindi NON USATE MAI i metodi speciali :-)

(vedremo poi come definirli)

Esistono alcuni metodi speciali (che iniziano per __ ) che realizzano le funzionalità degli operatori usati nelle espressioni/istruzioni. Per es.

  • __eq__ che implementa l'operatore ==
  • __add__ che implementa l'operatore +
  • __mul__ che implementa l'operatore *
  • __len__ che implementa la funzione len

Tutti gli oggetti che implementano questi metodi possono essere confrontati, sommati, moltiplicati, contati, ...

Ecco come mai le stringhe possono essere sommate o moltiplicate, hanno un proprio metodo __add__ e __mul__

Questo vi sarà utile quando vedremo come costruire oggetti che possiamo confrontare sommare, o di cui vogliamo calcolare la lunghezza (se contengono elementi) ...

In [73]:
N = 3
N.__add__(5)    # questo è cosa succede veramente se scrivo N + 5
Out[73]:
8
In [74]:
# i numeri complessi hanno le 4 operazioni come gli altri numeri
# (ma sono implementate diversamente)
X_complesso = 3 + 2j     # si usa j al posto di i=sqrt(-1)
Y_complesso = 7 - 6j
Z_complesso = X_complesso + Y_complesso           # somma complessa
Z_complesso,  Z_complesso.real, Z_complesso.imag
Out[74]:
((10-4j), 10.0, -4.0)

Funzioni: come definire parti di programma riusabili¶

  • MAI: copiare e incollare più volte lo stesso pezzo di codice
  • SEMPRE: definisci una funzione separata e chiamala quante volte vuoi

Sintassi: (come si scrive)¶

def nome_della_funzione( argomenti ):
    'docstring che descrive cosa fa'
    istruzioni che calcolano il risultato
    return risultato

Il corpo della funzione DEVE essere indentato (in genere di 4 spazi)

Gli argomenti sono nomi che indicano le informazioni necessarie perchè la funzione possa svolgere il suo compito

NOTA: i nomi degli argomenti sono variabili disponibili SOLO nel corpo della funzione (la parte indentata)

Il risultato è il dato che la funzione ha calcolato e che viene fornito al programma che la usa

ESEMPIO: calcolare l'altezza media di un gruppo¶

In [75]:
# come si definisce la funzione
def media_altezze(altezze):
    'calcolo la media di un gruppo di altezze'   # docstring
    somma_altezze = sum(altezze)
    media_altezze = somma_altezze/len(altezze)
    return media_altezze                         # valore risultante
In [76]:
## Come la si usa/chiama la funzione
# se abbiamo una lista di altezze 
elenco_altezze = [ 170, 190, 165, 155, 186, 172, ]   
# e ne calcoliamo la media chiamando la funzione 'media_altezze'
media = media_altezze(elenco_altezze)  # e mettendo il risultato in una variabile           
# otteniamo
media                                                
Out[76]:
173.0

NOTATE CHE¶

  • i nomi che ho usato nella definizione della funzione sono altezze (parametri formali, i dati che la funzione riceve da chi la chiama)
  • i nomi che ho usato nel codice che USA la funzione sono elenco_altezze
    (parametri attuali, i dati che effettivamente voglio fornire a questa particolare chiamata della funzione)

Stile: è meglio usare nomi diversi per i parametri formali e per gli attuali per evitare di confondersi

Ancora questioni di stile: identificatori parlanti¶

  • scegliete sempre un nome di funzione che vi ricorda bene cosa fa
    • GOOD: calcola_altezza_media
    • BAD: pippo
  • scegliete sempre i nomi degli argomenti in modo che sia chiaro quali informazioni dovete fornire alla funzione
    • GOOD: altezze
    • BAD: lista
  • scegliete sempre i nomi delle variabili in modo che vi sia chiaro cosa contengono
    • GOOD: somma_altezze
    • BAD: sa

Namespaces: dove stanno i nomi delle variabili e funzioni¶

  • globale: è il livello più esterno del vostro programma, in cui scrivete le istruzioni direttamente appoggiate al bordo sinistro
    • variabili globali: accessibili dentro a tutte le funzioni e metodi (ALTAMENTE SCONSIGLIATE perchè creano errori difficili da trovare)
    • funzioni globali: accessibili a tutte le altre funzioni del file
  • modulo: è il contenuto di un file importato con import, ci trovate le variabili e le funzioni definite in quel file. Le ottenete scrivendo modulo.variabile oppure modulo.funzione(argomenti)
  • locale: ogni funzione usa delle variabili proprie, dette variabili locali, che sono accessibili SOLO nelle istruzioni del corpo della funzione o di una sua sottofunzione. Gli argomenti della funzione sono anche loro variabili locali alla funzione.

ATTENZIONE una variabile locale può nascondere una variabile globale

In [77]:
variabile = 42                # definisco una variabile globale

def funzione_di_prova( argomento ):
    variabile = argomento     # qui la ridefinisco come locale
    print(variabile, 'stampo la locale')

print(variabile, 'globale')
funzione_di_prova(92)
print(variabile, 'globale invariata')
funzione_di_prova(667)
42 globale
92 stampo la locale
42 globale invariata
667 stampo la locale

Chiamata delle funzioni e
vita delle variabili locali

Le variabili locali ad una funzione vengono CREATE nel momento in cui la funzione viene ESEGUITA (e non quando viene definita)

Ogni esecuzione crea un nuovo gruppo di variabili locali della funzione

Per cui le funzioni possono richiamare se stesse senza problemi, ciascuna chiamata userà uno spazio di memoria personale separato dagli spazi delle altre chiamate

Le variabili locali sono rilasciate quando si esce
dalla funzione
e si torna al programma che l'ha chiamata

NOTA: la memoria che viene rilasciata è quella dei RIFERIMENTI.
Gli oggetti creati dalla funzione possono sopravviverle

MA QUESTO FA SPRECARE UN SACCO DI MEMORIA ???

NO, esiste un processo in background, il garbage collector che esamina la memoria continuamente e libera tutti gli oggetti che non sono più raggiungibili dai programmi in esecuzione

In [80]:
## Esempio di creazione di un oggetto dentro una funzione
def concatena(prima_parte, seguito):
    # costruisco una nuova stringa
    nuovo_testo = prima_parte + ' ' + seguito
    return nuovo_testo    # e la ritorno
A = 'inizio '
B = 'fine'
C = concatena(A, B)
print(A, B, C, sep='\n')
print(prima_parte)        
# errore perchè 'nuovo_testo' non esiste nel namespace globale
inizio 
fine
inizio  fine
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
/tmp/ipykernel_9389/2666591040.py in <cell line: 10>()
      8 C = concatena(A, B)
      9 print(A, B, C, sep='\n')
---> 10 print(prima_parte)
     11 # errore perchè 'nuovo_testo' non esiste nel namespace globale

NameError: name 'prima_parte' is not defined

Ancora booleani: come scegliere
alternative diverse

  • gli operatori di confronto sono le espressioni booleane più semplici
  • potete combinarli con gli operatori and, or e not
  • not ha priorità su and che l'ha su or
  • usate le parentesi altrimenti

E' quindi possibile scrivere condizioni complesse

piove = not soleggiato or strade_bagnate
porto_l_ombrello = piove or sole_abbacinante
strade_bagnate = ha_piovuto or innaffiamento_automatico_acceso

Condizioni e percorsi alternativi¶

Per scegliere parti diverse di codice si usa l'istruzione if e delle condizioni (booleane) che valgono True o False

Sintassi:

if condizione1:
    istruzioni eseguite 
    se condizione1 è True
elif condizione2:         # opzionale
    istruzioni eseguite 
    se condizione1 è False e condizione2 è True
else:                     # opzionale
    istruzioni eseguite 
    se condizione1 e condizione2 sono False

Momento Wooclap¶

Quanto valgono queste espressioni booleane ?¶

Cosa stampa il programma ?¶

Screenshot%20from%202022-10-09%2020-28-21.png

In [81]:
## Soluzioni
True and not False or True and False or not True
# è lo stesso che scrivere
(True and (not False) ) or (True and False) or (not True)
# cioè
(True and True) or False or False
Out[81]:
True
In [ ]:
# Visto che True == 1  e che False == 0
True+False/True+True*True-False
# è lo stesso che
1 +  0  /  1 +  1 *  1 -  0
In [ ]:
# soluzione
is_raining   = True
got_umbrella = False
have_money   = True;
if not is_raining:
    print('go out')
elif not got_umbrella and have_money:
    print('buy umbrella and go out')
elif got_umbrella:
    print('go out since got umbrella')
else:
    print('stay home')