Skip to content
HackoryWEB SECURITY ACADEMYProgramming

Unit 09 · Funciones · Lesson 05

Funciones que usan otras funciones

Dentro de una función podés llamar a otra y usar lo que devuelve.

Lesson content is in Spanish.

Python in your browser

The first time, Python downloads about 5 MB (only once; then it stays saved). If you can, use Wi-Fi.

Python is already saved in this browser: it will not download again.

Python downloads when you start reading.
  1. 01Understand
  2. 02Try
  3. 03Explain

The situation

Un ticket tiene una línea por producto, con su precio total. Ya tenés una función que calcula ese precio: la función que arma la línea puede usarla en lugar de repetir la cuenta.

Understand each piece

  • Llamar desde otra función

    Dentro de una función podés llamar a otra y guardar lo que devuelve: importe = precio_total(cantidad, precio_unitario).

  • Variables locales

    Las variables que creás dentro de una función solo existen ahí. Otra función no las ve: si necesita un valor, lo recibe como argumento o llama a la función que lo devuelve.

Example

def precio_total(cantidad, precio_unitario):
    return cantidad * precio_unitario

def linea(producto, cantidad, precio_unitario):
    importe = precio_total(cantidad, precio_unitario)
    return f"{cantidad} {producto}: ${importe}"

print(linea("cuadernos", 6, 3))

linea llama a precio_total, que devuelve 18. Con ese valor arma el texto y lo devuelve. Se muestra 6 cuadernos: $18.

Before moving on: what will happen?

¿Qué va a mostrar este programa?
def doble(n):
    return n * 2

def cuadruple(n):
    return doble(doble(n))

print(cuadruple(3))

Your mission

La línea del ticket

La función precio_total ya está escrita en el editor. Debajo, definí linea_de_ticket con tres parámetros: producto, cantidad y precio_unitario. Tiene que llamar a precio_total y devolver (no mostrar) un texto con este formato. Por ejemplo, linea_de_ticket("cuaderno", 6, 3) devuelve: cuaderno: 6 x $3 = $18 Escribí solo la función: la prueba la llama con distintos datos. Si la llamás para probarla, borrá esa llamada antes de comprobar, porque la prueba compara toda la salida.

  1. def linea_de_ticket(producto, cantidad, precio_unitario):
  2. importe = precio_total(cantidad, precio_unitario).
  3. return f"{producto}: {cantidad} x ${precio_unitario} = ${importe}".

If you get stuck

One hint at a time: the first points the way and the last almost solves it.

The key idea

Una función puede usar otra: así cada cuenta se escribe una sola vez.

Solve with help

If you have already tried, you can see a reference solution. The lesson is marked as solved with help and adds no XP.