Le

Le basi in Python

113 esercizi

Informazioni su Le basi

Python è un linguaggio di programmazione dinamico e fortemente tipizzato. Fa uso sia del duck typing che della tipizzazione graduale, tramite i type hints. Gli stili di programmazione imperativo, dichiarativo (ad esempio funzionale) e orientato agli oggetti sono tutti supportati, ma al suo interno in Python tutto è un oggetto.

Python dà molta importanza alla leggibilità del codice e (come Haskell) usa l'indentazione significativa per indicare le definizioni di funzioni, metodi e classi.

Python è stato creato da Guido van Rossum e pubblicato per la prima volta nel 1991. La Python Software Foundation gestisce e indirizza le risorse per lo sviluppo di Python e CPython, e riceve proposte di modifica del linguaggio dai membri della comunità tramite le Python Enhancement Proposals, o PEP.

La documentazione completa della versione attuale è disponibile su docs.python.org.


Questo primo concetto introduce 4 funzionalità principali del linguaggio Python:

  1. Assegnazione dei nomi (variabili e costanti),
  2. Funzioni (le parole chiave def e return),
  3. Commenti, e
  4. Docstring.
Note

In generale, i contenuti, i test e gli strumenti di analisi della traccia Python seguono le convenzioni di stile descritte in PEP 8 e PEP 257 per lo stile del codice Python, con l'ulteriore (forte) suggerimento di non usare nomi di variabili di una sola lettera.

Lo zen di Python (PEP 20) e What is Pythonic? espongono ulteriori filosofie.

Nella traccia Python, le variabili sono sempre scritte in snake_case, e le costanti in SCREAMING_SNAKE_CASE

Assegnazione dei nomi (variabili e costanti)

In Python non ci sono parole chiave per creare variabili o costanti. I programmatori possono invece associare dei nomi (detti anche variabili) a qualsiasi tipo di oggetto usando l'operatore di assegnazione =: <name> = <value>. Un nome può essere riassegnato (o riassociato) a valori diversi (tipi di oggetto diversi) nel corso della sua vita.

Ad esempio, my_first_variable può essere riassegnata molte volte usando =, e può riferirsi a tipi di oggetto diversi a ogni riassegnazione:

>>> my_first_variable = 1  # my_first_variable bound to an integer object of value one.
>>> my_first_variable = 2  # my_first_variable re-assigned to integer value 2.

>>> print(type(my_first_variable))
<class 'int'>

>>> print(my_first_variable)
2

>>> my_first_variable = "Now, I'm a string." # <--You may re-bind a name to a different object type and value.
>>> print(type(my_first_variable))
<class 'str'>

>>> my_first_variable = 'You can call me "str".' # <--Strings can be declared using single or double quote marks.
>>> print(my_first_variable)
You can call me "str".

>>> import collections
>>> my_first_variable = collections.Counter([1,1,2,3,3,3,4,5,6,7]) # <--Now my_first_variable has been re-bound to a Counter object.
>>> print(type(my_first_variable))
<class 'collections.Counter'>

>>> print(my_first_variable)
Counter({3: 3, 1: 2, 2: 1, 4: 1, 5: 1, 6: 1, 7: 1})

Costanti

Le costanti sono nomi che dovrebbero essere assegnati una sola volta in un programma. Dovrebbero essere definite a livello di modulo (file) e in genere sono visibili a tutte le funzioni e le classi del programma. Usare SCREAMING_SNAKE_CASE segnala che il nome non dovrebbe essere riassegnato, né il suo valore modificato.

# All caps signal that this is intended as a constant.
MY_FIRST_CONSTANT = 16

# Re-assignment will be allowed by the compiler & interpreter,
# but this is VERY strongly discouraged.
# Please don't do this, it could create problems in your program!
MY_FIRST_CONSTANT = "Some other value"

Funzioni

In Python, le unità di funzionalità sono incapsulate in funzioni, che sono a loro volta oggetti (è un caso di turtles all the way down).

Le funzioni possono essere eseguite da sole, passate come argomenti ad altre funzioni, annidate o associate a una classe. Quando le funzioni sono associate a un nome di classe, vengono chiamate metodi. Funzioni e classi correlate (con i loro metodi) possono essere raggruppate nello stesso file o modulo, e importate in parte o del tutto per essere usate in altri programmi.

La parola chiave def inizia una definizione di funzione. Ogni funzione può avere zero o più parametri formali tra parentesi (), seguiti dai due punti :. Le istruzioni del corpo della funzione iniziano sulla riga successiva a def e devono essere indentate in un blocco:

# The body of a function is indented by 2 spaces & prints the sum of the numbers.
def add_two_numbers(number_one, number_two):
  total = number_one + number_two
  print(total)  

>>> add_two_numbers(3, 4)
7


# Inconsistent indentation in your code blocks will raise an error.
>>> def add_three_numbers_misformatted(number_one, number_two, number_three):
...     result = number_one + number_two + number_three   # This was indented by 4 spaces.
...    print(result)     # <--This was only indented by 3 spaces.
...
...
  File "<stdin>", line 3
    print(result)
    ^
IndentationError: unindent does not match any outer indentation level

Le funzioni restituiscono esplicitamente un valore o un oggetto tramite la parola chiave return:

# Function definition on first line, explicit return used on final line.
def add_two_numbers(number_one, number_two):
  return number_one + number_two   


# Calling the function in the Python shell returns the sum of the numbers.
>>> add_two_numbers(3, 4)
7

# Assigning the function call to a variable and printing 
# the variable will also return the value.
>>> sum_with_return = add_two_numbers(5, 6)
>>> print(sum_with_return)
11

Le funzioni che non hanno un'espressione esplicita dopo un return restituiscono implicitamente l'oggetto None. I dettagli di None saranno trattati in un concetto successivo. Ai fini di questo esercizio e di questa spiegazione, None è un segnaposto che rappresenta nulla, o il valore nullo:


# This function will return `None`
def square_a_number(number):
    square = number * number
    return # <-- note that this return is not followed by an expression

# Calling the function in the Python shell appears 
# to not return anything at all.
>>> square_a_number(2)
>>>


# Using print() with the function call shows that 
# the function is actually returning the **None** object.
>>> print(square_a_number(2))
None

Anche le funzioni che omettono return restituiscono implicitamente l'oggetto None. Questo significa che se non usi return in una funzione, Python restituirà l'oggetto None al posto tuo.


# This function omits a return keyword altogether
def add_two_numbers(number_one, number_two):
  result = number_one + number_two

>>> add_two_numbers(5, 7)
>>> print(add_two_numbers(5, 7))
None

# Assigning the function call to a variable and printing 
# the variable will also show None.
>>> sum_without_return = add_two_numbers(5, 6)
>>> print(sum_without_return)
None

Chiamare le funzioni

Le funzioni si chiamano usando il loro nome seguito da (). La notazione con il punto (.) si usa per chiamare funzioni definite dentro una classe o un modulo.

>>> def raise_to_power(number, power):
...     return number ** power
...

>>> raise_to_power(3,3) # Invoking the function with the arguments 3 and 3.
27


# A mis-match between the number of parameters and the number of arguments will raise an error.
>>> raise_to_power(4,)
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: raise_to_power() missing 1 required positional argument: 'power'


# Calling methods or functions in classes and modules.
>>> start_text = "my silly sentence for examples."
>>> str.upper(start_text)  # <--Calling the upper() method from the built-in str class on start_text.
'MY SILLY SENTENCE FOR EXAMPLES.'

# Because a string is an instance of the str class, methods can also be called on them "directly".
>>> start_text = "my silly sentence for examples."
>>> start_text.upper()  # <--Calling the upper() method on start_text directly.
'MY SILLY SENTENCE FOR EXAMPLES.'

# Alternatively, we can skip the variable assignment (although this gets messy quick).
>>> "my silly sentence for examples.".upper()
'MY SILLY SENTENCE FOR EXAMPLES.'


# Importing the math module
>>> import math
>>> math.pow(2,4)  # <--Calling the pow() function from the math module.
16.0

I commenti

I commenti in Python iniziano con un # che non fa parte di una stringa e terminano alla fine della riga. A differenza di molti altri linguaggi di programmazione, Python non supporta i marcatori di commento su più righe. Ogni riga di un blocco di commento deve iniziare con il carattere #.

I commenti vengono ignorati dall'interprete:

# This is a single line comment.

x = "foo"  # This is an in-line comment.

# This is a multi-line
# comment block over multiple lines --
# these should be used sparingly.

Docstring

La prima istruzione del corpo di una funzione può essere, facoltativamente, una docstring, che riassume in modo conciso lo scopo della funzione o dell'oggetto. Le docstring si dichiarano usando tripli doppi apici (""") indentati allo stesso livello del blocco di codice:

# An example from PEP257 of a multi-line docstring
# reformatted to use Google style non-type hinted docstrings.
# Some additional details can be found in the Sphinx documentation:
# https://www.sphinx-doc.org/en/master/usage/extensions/napoleon.html#getting-started

def complex(real=0.0, imag=0.0):
    """Form a complex number.

    Keyword Arguments:
        real (float): The real part of the number (default 0.0)
        imag (float): The imaginary part of the number (default 0.0)
        
    """

    if imag == 0.0 and real == 0.0:
        return complex_zero

Le docstring vengono lette dagli strumenti automatici di documentazione e sono restituite chiamando l'attributo speciale .__doc__ sul nome della funzione, del metodo o della classe. Sono consigliate per programmi di qualsiasi dimensione in cui serve la documentazione, e le loro convenzioni sono descritte in PEP257.

Le docstring possono anche funzionare come test unitari leggeri, che possono essere letti ed eseguiti da PyTest, oppure importando il modulo doctest. I test e doctest saranno trattati in un concetto successivo.

# An example on a user-defined function using a Google style docstring. 
>>> def raise_to_power(number, power):
    """Raise a number to an arbitrary power.

    Parameters:
        number (int): The base number.
        power (int): The power to raise the base number to.
    
    Returns:
        int: The number raised to the specified power.
    
    Takes a number and raises it to the specified power, returning the result.

    """

    return number ** power
...

# Calling the .__doc__ attribute of the function and printing the result.
>>> print(raise_to_power.__doc__)
Raise a number to an arbitrary power.

Parameters:
    number (int): The base number.
    power (int): The power to raise the base number to.

Returns:
    int: The number raised to the specified power.

Takes a number and raises it to the specified power, returning the result.

...

# Printing the __doc__ attribute of the built-in type: str.
>>> print(str.__doc__)
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 'utf-8'.
errors defaults to 'strict'.
Modifica tramite GitHub Il collegamento si apre in una nuova finestra o scheda

Impara Le basi