Es. Python tutorial - Moduli e pacchetti

Es. Python tutorial - Moduli e pacchetti Es. Python tutorial - Moduli e pacchetti

Es. Python tutorial - Moduli e pacchetti

Versione italiana

Esercizi

1. Creazione di un Modulo

Crea un modulo chiamato math_utils.py che contenga una funzione square(n) che restituisce il quadrato di un numero. Importa il modulo in un altro script e usa la funzione.

2. Uso di from ... import ...

Crea un modulo string_utils.py con una funzione reverse_string(s) che restituisce la stringa inversa. Importa solo questa funzione in un altro script e usala.

3. Creazione di un Pacchetto

Crea un pacchetto chiamato geometry con due moduli:

  • circle.py che contiene una funzione area(radius) per calcolare l’area di un cerchio.
  • rectangle.py che contiene una funzione area(length, width) per calcolare l’area di un rettangolo.
    Scrivi uno script che usi entrambi i moduli.

4. Modulo con Variabili

Crea un modulo config.py che contiene una variabile VERSION = "1.0". Importa il modulo in un altro script e stampa la versione.

5. Importazione con Alias

Crea un modulo operations.py con una funzione add(a, b) che restituisce la somma di due numeri. Importa il modulo con un alias e usa la funzione.

6. Uso di __name__ == "__main__"

Crea un modulo runner.py con una funzione greet() che stampa "Hello!". Fai in modo che la funzione venga eseguita solo se il modulo viene eseguito direttamente.

7. Ricaricare un Modulo

Scrivi un modulo counter.py con una variabile count = 0 e una funzione increment(). Importa il modulo e ricaricalo per resettare count senza riavviare lo script.

8. Importazione Relativa

Crea un pacchetto shapes con un modulo square.py che ha una funzione area(side). All’interno dello stesso pacchetto, crea un altro modulo main.py che importa square.py usando un’importazione relativa.

9. Uso di dir()

Crea un modulo utils.py con almeno tre funzioni diverse. Importa il modulo e usa dir(utils) per elencarne il contenuto.

10. Gestione degli Errori nell’Import

Scrivi uno script che tenta di importare un modulo inesistente e gestisce l’errore con un blocco try-except.


Soluzioni

# 1. Creazione di un Modulo
# math_utils.py
def square(n):
    return n * n

# script.py
import math_utils
print(math_utils.square(4))  # Output: 16

# 2. Uso di `from ... import ...`
# string_utils.py
def reverse_string(s):
    return s[::-1]

# script.py
from string_utils import reverse_string
print(reverse_string("hello"))  # Output: "olleh"

# 3. Creazione di un Pacchetto
# geometry/circle.py
def area(radius):
    return 3.14159 * radius * radius

# geometry/rectangle.py
def area(length, width):
    return length * width

# script.py
from geometry.circle import area as circle_area
from geometry.rectangle import area as rectangle_area

print(circle_area(5))  # Output: 78.53975
print(rectangle_area(4, 6))  # Output: 24

# 4. Modulo con Variabili
# config.py
VERSION = "1.0"

# script.py
import config
print(config.VERSION)  # Output: "1.0"

# 5. Importazione con Alias
# operations.py
def add(a, b):
    return a + b

# script.py
import operations as op
print(op.add(3, 7))  # Output: 10

# 6. Uso di `__name__ == "__main__"`
# runner.py
def greet():
    print("Hello!")

if __name__ == "__main__":
    greet()  # Output: "Hello!"

# 7. Ricaricare un Modulo
# counter.py
count = 0

def increment():
    global count
    count += 1
    return count

# script.py
import counter
print(counter.increment())  # Output: 1
import importlib
importlib.reload(counter)
print(counter.count)  # Output: 0

# 8. Importazione Relativa
# shapes/square.py
def area(side):
    return side * side

# shapes/main.py
from .square import area
print(area(4))  # Output: 16

# 9. Uso di `dir()`
# utils.py
def foo():
    pass

def bar():
    pass

def baz():
    pass

# script.py
import utils
print(dir(utils))  # Output: ['bar', 'baz', 'foo', ...]

# 10. Gestione degli Errori nell’Import
# script.py
try:
    import non_existent_module
except ModuleNotFoundError:
    print("Modulo non trovato!")  # Output: "Modulo non trovato!"

English version

Exercises

1. Creating a Module

Create a module called math_utils.py that contains a function square(n) that returns the square of a number. Import the module into another script and use the function.

2. Using from ... import ...

Create a module string_utils.py with a function reverse_string(s) that returns the reverse string. Import only this function into another script and use it.

3. Creating a Package

Create a package called geometry with two modules:

  • circle.py that contains a function area(radius) to calculate the area of ​​a circle.
  • rectangle.py that contains a function area(length, width) to calculate the area of ​​a rectangle. Write a script that uses both modules.

4. Module with Variables

Create a module config.py that contains a variable VERSION = "1.0". Import the module into another script and print the version.

5. Importing with Aliases

Create a module operations.py with a function add(a, b) that returns the sum of two numbers. Import the module with an alias and use the function.

6. Using __name__ == "__main__"

Create a module runner.py with a function greet() that prints "Hello!". Make the function run only if the module is run directly.

7. Reloading a Module

Write a module counter.py with a variable count = 0 and a function increment(). Import the module and reload it to reset count without restarting the script.

8. Relative Import

Create a shapes package with a square.py module that has an area(side) function. Inside the same package, create another main.py module that imports square.py using a relative import.

9. Using dir()

Create a utils.py module with at least three different functions. Import the module and use dir(utils) to list its contents.

10. Import Error Handling

Write a script that attempts to import a nonexistent module and handles the error with a try-except block.


Solutions

#1. Creating a Form
# math_utils.py
def square(n):
 return n * n

# script.py
import math_utils
print(math_utils.square(4)) # Output: 16

#2. Using `from ... import ...`
# string_utils.py
def reverse_string(s):
 return s[::-1]

# script.py
from string_utils import reverse_string
print(reverse_string("hello")) # Output: "olleh"

#3. Creating a Package
# geometry/circle.py
def area(radius):
 return 3.14159 * radius * radius

# geometry/rectangle.py
def area(length, width):
 return length * width

# script.py
from geometry.circle import area as circle_area
from geometry.rectangle import area as rectangle_area

print(circle_area(5)) # Output: 78.53975
print(rectangle_area(4, 6)) # Output: 24

#4. Module with Variables
# config.py
VERSION = "1.0"

# script.py
import config
print(config.VERSION) # Output: "1.0"

#5. Import with Alias
# operations.py
def add(a, b):
 return a + b

# script.py
import operations as op
print(op.add(3, 7)) # Output: 10

#6. Using `__name__ == "__main__"`
# runner.py
def greet():
 print("Hello!")

if __name__ == "__main__":
 greet() # Output: "Hello!"

#7. Reload a Form
# counter.py
count = 0

def increment():
 global count
 count += 1
 return count

# script.py
import counter
print(counter.increment()) # Output: 1
import importlib
importlib.reload(counter)
print(counter.count) # Output: 0

#8. Relative Import
# shapes/square.py
def area(side):
 return side * side

# shapes/main.py
from .square import area
print(area(4)) # Output: 16

# 9. Using `dir()`
# utils.py
def foo():
 pass

def bar():
 pass

def baz():
 pass

# script.py
import utilities
print(dir(utils)) # Output: ['bar', 'baz', 'foo', ...]

#10. Error Handling in Import
# script.py
try:
import non_existent_module
except ModuleNotFoundError:
print("Module not found!") # Output: "Module not found!"

Commenti