Le funzioni senza return sono utili quando si desidera organizzare il codice in blocchi riutilizzabili che stampano messaggi, modificano dati o eseguono azioni, senza restituire un valore al chiamante.
In Python, ogni funzione restituisce un valore.
Se una funzione non include return, restituirà automaticamente None.
A volte la funzione serve solo a notificare l’utente:
# Prices of items sold today
prices = [12.99, 23.50, 4.99, 8.75, 15.00]
def total_sales(prices):
print(f"Today's total sales: $", sum(prices))
total_sales(prices)
print) ma non restituisce un valore.Funzioni void sono spesso usate per modificare liste o dizionari:
def update_inventory(inventory, items_sold):
for product, quantity_sold in items_sold.items():
inventory[product] -= quantity_sold
# Inventory dictionary
inventory = {"apples": 50, "bananas": 75, "oranges": 100}
# Items sold
items_sold = {"apples": 5, "oranges": 15}
# Update inventory
update_inventory(inventory, items_sold)
print("Updated inventory:", inventory)
inventory direttamente senza bisogno di return.Le funzioni void possono anche attivare altre funzioni:
inventory = {"apples": 17, "bananas": 75, "oranges": 2, "grapes": 50}
def restock(product, inventory, restock_amount):
inventory[product] += restock_amount
print(f"Restock order placed for {product}. New stock level: {inventory[product]} units.")
def check_stock_levels(inventory, threshold):
for product, quantity in inventory.items():
if quantity < threshold:
restock(product, inventory, 50)
check_stock_levels(inventory, 30)
print("Final inventory status:", inventory)
check_stock_levels() chiama restock() per i prodotti sotto soglia.In Python, se una funzione non ha un’istruzione return, cosa restituisce?
""None ✅