Funciones sin Retorno
Las funciones sin una declaración return
son útiles cuando deseas estructurar tu código en secciones reutilizables que realizan tareas como imprimir mensajes, modificar datos o ejecutar acciones dentro de tu programa.
Nota
En Python, cada función devuelve un valor. Si una función no incluye explícitamente una declaración
return
, automáticamente devolveráNone
.
Veamos cómo Alex demuestra la creación y uso de funciones que no devuelven un valor:
La mejor manera de entender cómo usamos funciones sin declaración return
es verlas en acción, así que veamos algunos ejemplos.
Imprimir Información en la Consola
A veces, el propósito de una función es simplemente notificar al usuario de un evento específico o resultado imprimiendo información en la consola.
Por ejemplo, no hay necesidad de devolver un valor en la función total_sales()
porque su función principal es realizar un cálculo y mostrar el resultado inmediatamente:
1234567# 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
El orden en el que se declaran los datos y funciones no importa. La única regla importante es que una función debe ser definida antes de ser llamada.
Modificando una Estructura de Datos
Los desarrolladores a menudo necesitan crear funciones que modifiquen una estructura de datos, como una lista o un diccionario, sin devolver un valor.
Por ejemplo, la función update_inventory()
ajusta los niveles de inventario basándose en los items_sold
. Dado que la función modifica directamente el diccionario inventory
, no es necesario devolver nada:
12345678910111213141516171819202122232425# 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)
Llamando a Otra Función
Es común crear funciones que monitorean condiciones específicas y activan otras funciones cuando es necesario.
Por ejemplo, la función check_stock_levels()
verifica si el nivel de stock de algún producto cae por debajo de un umbral establecido. Si es así, llama a la función restock()
para ordenar más inventario.
Este enfoque no requiere devolver un valor, ya que el objetivo principal es iniciar el proceso de reabastecimiento:
12345678910111213141516171819202122232425# 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)
¡Gracias por tus comentarios!
Pregunte a AI
Pregunte a AI
Pregunte lo que quiera o pruebe una de las preguntas sugeridas para comenzar nuestra charla
Awesome!
Completion rate improved to 2.17
Funciones sin Retorno
Desliza para mostrar el menú
Las funciones sin una declaración return
son útiles cuando deseas estructurar tu código en secciones reutilizables que realizan tareas como imprimir mensajes, modificar datos o ejecutar acciones dentro de tu programa.
Nota
En Python, cada función devuelve un valor. Si una función no incluye explícitamente una declaración
return
, automáticamente devolveráNone
.
Veamos cómo Alex demuestra la creación y uso de funciones que no devuelven un valor:
La mejor manera de entender cómo usamos funciones sin declaración return
es verlas en acción, así que veamos algunos ejemplos.
Imprimir Información en la Consola
A veces, el propósito de una función es simplemente notificar al usuario de un evento específico o resultado imprimiendo información en la consola.
Por ejemplo, no hay necesidad de devolver un valor en la función total_sales()
porque su función principal es realizar un cálculo y mostrar el resultado inmediatamente:
1234567# 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
El orden en el que se declaran los datos y funciones no importa. La única regla importante es que una función debe ser definida antes de ser llamada.
Modificando una Estructura de Datos
Los desarrolladores a menudo necesitan crear funciones que modifiquen una estructura de datos, como una lista o un diccionario, sin devolver un valor.
Por ejemplo, la función update_inventory()
ajusta los niveles de inventario basándose en los items_sold
. Dado que la función modifica directamente el diccionario inventory
, no es necesario devolver nada:
12345678910111213141516171819202122232425# 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)
Llamando a Otra Función
Es común crear funciones que monitorean condiciones específicas y activan otras funciones cuando es necesario.
Por ejemplo, la función check_stock_levels()
verifica si el nivel de stock de algún producto cae por debajo de un umbral establecido. Si es así, llama a la función restock()
para ordenar más inventario.
Este enfoque no requiere devolver un valor, ya que el objetivo principal es iniciar el proceso de reabastecimiento:
12345678910111213141516171819202122232425# 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)
¡Gracias por tus comentarios!