CODEZEROINTERACTIVE

Chapter 10 / 15

Parte 4 — Acumuladores

Bucles while y for, menús repetitivos, break, continue, contadores y acumuladores.

Lesson 554%

5 / 26 lessons in this chapter

Parte 4 — Acumuladores

1 / 1 in this part

Current chapter

Chapter 10 — Bucles: repetir instrucciones

Self-paced

Parte 4 — Acumuladores

¿Qué es un acumulador?

Un acumulador guarda un total que aumenta o disminuye conforme ocurren operaciones.

Ejemplo:

python terminal
total_ingresos = 0

Cuando registramos un ingreso:

python terminal
total_ingresos += ingreso

Si recibimos:

text terminal
500
750
250

el acumulador terminará con:

text terminal
1500

Acumular valores con while

python terminal
contador = 1
total = 0

while contador <= 3:
    numero = int(input(f"Número {contador}: "))

    total += numero
    contador += 1

print("Total:", total)

Posible ejecución:

text terminal
Número 1: 100
Número 2: 200
Número 3: 300
Total: 600

Contador y acumulador no son lo mismo

python terminal
cantidad_gastos = 0
total_gastos = 0

cantidad_gastos registra cuántos gastos existen.

total_gastos registra cuánto dinero suman.

Después de registrar:

text terminal
Gasto 1: 200
Gasto 2: 350
Gasto 3: 150

Tendríamos:

text terminal
cantidad_gastos = 3
total_gastos = 700

Calcular un promedio

python terminal
cantidad_gastos = 3
total_gastos = 700

promedio_gastos = total_gastos / cantidad_gastos

print(round(promedio_gastos, 2))

Resultado:

text terminal
233.33

Debemos comprobar que cantidad_gastos sea mayor que cero antes de dividir.