Skip to content
HackoryWEB SECURITY ACADEMYProgramming

Unit 08 · Bucles: for y while · Lesson 02

Acumular valores

Un acumulador empieza en cero y suma en cada vuelta.

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 depósito prepara los pedidos uno por uno y quiere ver cómo crece el total en cada paso. sum() da solo el resultado final. Con un for y una variable que va sumando podés mostrar cada paso.

Understand each piece

  • Acumulador

    Es una variable que empieza en 0 antes del for y en cada vuelta suma el elemento: total = total + unidades.

  • Antes del for

    Si escribís total = 0 dentro del for, vuelve a cero en cada vuelta y al final solo queda el último valor.

  • +=

    total += unidades es una forma corta de escribir total = total + unidades. Las dos hacen lo mismo.

Example

ventas = [120, 450, 80]
total = 0
for venta in ventas:
    total = total + venta
print("Total:", total)

total empieza en 0. En la primera vuelta pasa a 120, en la segunda a 570 y en la tercera a 650. El print, fuera del for, muestra Total: 650.

Before moving on: what will happen?

¿Qué va a mostrar este programa?
for unidades in [20, 35, 15]:
    total = 0
    total = total + unidades
print(total)

Your mission

Prepará los pedidos uno por uno

La prueba crea la lista pedidos (unidades, puede estar vacía). Recorrela sumando y, en cada vuelta, mostrá el pedido y el acumulado. Al final mostrá el total. Con [20, 35, 20], la salida es: Pedido de 20 unidades. Acumulado: 20. Pedido de 35 unidades. Acumulado: 55. Pedido de 20 unidades. Acumulado: 75. Total a preparar: 75 unidades.

  1. Antes del for: total = 0.
  2. Dentro del for: total = total + unidades y después el print de la vuelta.
  3. Después del for, sin sangría: el print del total.

If you get stuck

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

The key idea

Un acumulador empieza antes del for y en cada vuelta suma el elemento actual.

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.