Conteúdo do Curso
Introdução ao Python
Introdução ao Python
Funções sem Retorno
Funções sem uma declaração return
são úteis quando você deseja estruturar seu código em seções reutilizáveis que realizam tarefas como imprimir mensagens, modificar dados ou executar ações dentro do seu programa.
Nota
Em Python, toda função retorna um valor. Se uma função não incluir explicitamente uma declaração
return
, ela retornará automaticamenteNone
.
Vamos ver como Alex demonstra a criação e uso de funções que não retornam um valor:
A melhor maneira de entender como usamos funções sem declaração return
é vê-las em ação, então vamos olhar alguns exemplos.
Imprimindo Informações no Console
Às vezes, o propósito de uma função é simplesmente notificar o usuário de um evento específico ou resultado imprimindo informações no console.
Por exemplo, não há necessidade de retornar um valor na função total_sales()
porque seu papel principal é realizar um cálculo e exibir o resultado imediatamente:
# 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)
Nota
A ordem em que os dados e funções são declarados não importa. A única regra importante é que uma função deve ser definida antes de ser chamada.
Modificando uma Estrutura de Dados
Os desenvolvedores frequentemente precisam criar funções que modificam uma estrutura de dados, como uma lista ou dicionário, sem retornar um valor.
Por exemplo, a função update_inventory()
ajusta os níveis de inventário com base nos items_sold
. Como a função modifica diretamente o dicionário inventory
, não há necessidade de retornar nada:
# Define the function that adjusts inventory levels def update_inventory(inventory, items_sold): # Iterate over each item in the dictionary for product, quantity_sold in items_sold.items(): # Decrease the inventory by the quantity sold for each product inventory[product] -= quantity_sold # Inventory dictionary inventory = { "apples": 50, "bananas": 75, "oranges": 100 } # Items sold dictionary items_sold = { "apples": 5, "oranges": 15 } # Update the inventory based on items sold update_inventory(inventory, items_sold) # Display the updated inventory print("Updated inventory:", inventory)
Chamando Outra Função
É comum criar funções que monitoram condições específicas e disparam outras funções quando necessário.
Por exemplo, a função check_stock_levels()
verifica se o nível de estoque de algum produto cai abaixo de um limite estabelecido. Se sim, ela chama a função restock()
para pedir mais inventário.
Essa abordagem não requer o retorno de um valor, pois o objetivo principal é iniciar o processo de reabastecimento:
# Dictionary representing the current stock of products inventory = { "apples": 17, "bananas": 75, "oranges": 2, "grapes": 50 } # Function to restock items that have low stock levels by adding a specified amount def restock(product, inventory, restock_amount): inventory[product] += restock_amount print(f"Restock order placed for {product}. New stock level: {inventory[product]} units.") # Function to check which items are below the stock threshold and trigger the `restock` function def check_stock_levels(inventory, threshold): for product, quantity in inventory.items(): if quantity < threshold: # If the stock is below the threshold, call the `restock` function to add 50 units restock(product, inventory, 50) # Checking the stock levels for all products in the inventory with a threshold of 30 units check_stock_levels(inventory, 30) # Display the final inventory after restocking print("Final inventory status:", inventory)
Obrigado pelo seu feedback!