Skip to content
HackoryWEB SECURITY ACADEMYProgramming

Unit 08 · Bucles: for y while · Lesson 03

Filtrar y contar dentro de un for

Un if dentro del for filtra y cuenta.

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

Una docente tiene las notas de un examen en una lista y quiere ver cuáles aprobaron (6 o más) y cuántas son. Hay que revisar cada nota y quedarse solo con las que cumplen.

Understand each piece

  • if dentro del for

    El if va con sangría dentro del for, y sus líneas llevan otra sangría más: ocho espacios en total. Así la decisión se toma en cada vuelta.

  • Contador

    Es un acumulador que suma 1 solo cuando se cumple la condición: cantidad = cantidad + 1.

Example

temperaturas = [31, 24, 30, 18, 33]
calurosos = 0
for t in temperaturas:
    if t >= 30:
        calurosos = calurosos + 1
print("Días de calor:", calurosos)

En cada vuelta, el if revisa una temperatura. Solo 31, 30 y 33 cumplen t >= 30, así que el contador llega a 3.

Before moving on: what will happen?

¿Qué va a mostrar este programa?
cuenta = 0
for nota in [5, 9, 6, 2]:
    if nota > 6:
        cuenta = cuenta + 1
print(cuenta)

Your mission

Contá las notas aprobadas

La prueba crea la lista notas (enteros de 0 a 10, puede estar vacía). Mostrá cada nota de 6 o más y, al final, cuántas fueron sobre el total. Con [9, 3, 6, 0, 7], la salida es: Nota aprobada: 9 Nota aprobada: 6 Nota aprobada: 7 Aprobadas: 3 de 5

  1. Antes del for: aprobadas = 0.
  2. Dentro del for: if nota >= 6: y adentro el print y aprobadas = aprobadas + 1.
  3. Al final: print(f"Aprobadas: {aprobadas} de {len(notas)}").

If you get stuck

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

The key idea

Con un if dentro del for, cada elemento se revisa por separado y solo los que cumplen se muestran o se cuentan.

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.