Errors & testing · Errores y pruebas
Three kinds of error
- A syntax error breaks the rules of Python, so the code will not run.
- A runtime error crashes the program while it is running.
- A logic error runs fine but gives the wrong answer.
Tres tipos de error
- Un error de sintaxis viola las reglas de Python, por lo que el código no se ejecutará.
- Un error en tiempo de ejecución provoca la caída del programa mientras está en ejecución.
- Un error lógico se ejecuta correctamente pero produce una respuesta incorrecta.
Syntax errors
- These are typos: a missing
:, an unclosed quote, a wrong indent. - Python refuses to start and shows you the line.
- Fix the spelling or punctuation, then run again.
Errores de sintaxis
- Son errores tipográficos: falta dos puntos
:, comillas sin cerrar, sangría incorrecta. - Python se niega a iniciar y te muestra la línea donde ocurrió.
- Corrige la ortografía o la puntuación, luego vuelve a ejecutarlo.
Runtime errors
- The code starts, then hits something it cannot do.
- Examples:
10 / 0, orint("hello"), or reading past the end of a list. - The program stops at that line with a message.
Errores en tiempo de ejecución
- El código comienza, pero encuentra algo que no puede procesar.
- Ejemplos:
10 / 0, oint("hello"), o leer más allá del final de una lista. - El programa se detiene en esa línea con un mensaje de error.
Logic errors
- The program runs to the end but the result is wrong.
- Example: using
-where you meant+, or stopping a loop too early. - These are the hardest to find — the computer did exactly what you wrote.
Errores lógicos
- El programa se ejecuta hasta el final, pero el resultado es incorrecto.
- Ejemplo: usar
-cuando querías usar+, o detener un bucle demasiado pronto. - Son los más difíciles de encontrar — la computadora hizo exactamente lo que escribiste.
Read the traceback
- When a program crashes, Python prints a traceback.
- Read the last line first: it names the error and what went wrong.
- The line number tells you where to look.
Lee la traza de error (traceback)
- Cuando un programa falla, Python imprime una traza de error.
- Lee la última línea primero: indica el tipo de error y qué salió mal.
- El número de línea te dice dónde buscar.
Traceback (most recent call last):
File "<program>", line 2, in <module>
print(10 / 0)
ZeroDivisionError: division by zero
Test with chosen data
- Do not trust code until you have tested it.
- Use normal data, boundary data (like
0), and extreme data. - Check each answer against what you worked out by hand.
Prueba con datos seleccionados
- No confíes en el código hasta haberlo probado.
- Usa datos normales, datos límite (como
0) y datos extremos. - Verifica cada resultado contra lo que calculaste manualmente.
def square(n):
return n * n
print(square(3)) # normal -> 9
print(square(0)) # boundary -> 0
print(square(-2)) # negative -> 4
Common mistakes
- A syntax error stops the program before it runs, so fix those first.
- Catch a specific error with
except ValueError:, not a bareexcept:. - Test the tricky cases (empty, zero, the biggest), not just the easy one.
Errores comunes
- Un error de sintaxis detiene el programa antes de que se ejecute, así que corrígelos primero.
- Captura un error específico con
except ValueError:, no con unexcept:genérico. - Prueba los casos difíciles (vacío, cero, el valor máximo), no solo los fáciles.
Now you try
- Each task has a logic error to fix, or a crash to prevent.
- Press Check answer to test your fix against several cases.
Ahora tú intentas
- Cada tarea tiene un error lógico para corregir, o una caída que prevenir.
- Presiona Check answer (Verificar respuesta) para probar tu corrección contra varios casos.
Find and fix a bug · Encontrar y corregir un error
Testing is a cycle: run it, see what's wrong, fix, run again. · Las pruebas son un ciclo: ejecútalas, observa qué está mal, corrige, vuelve a ejecutar.
This function should add a and · y b, but it has a logic error — it subtracts. Fix it so it returns the sum. · Esta función debería sumar a y b, pero tiene un error lógico: resta. Corrígela para que devuelva la suma.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
sum_to(n) should return 1 + 2 + ... + n, but it stops one number too early (an off-by-one logic error). Fix the range so it includes n. · sum_to(n) debería devolver 1 + 2 + ... + n, pero se detiene un número antes de tiempo (error de lógica off-by-one). Corrige el range para que incluya n.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
Write safe_divide(a, b) that returns a / b, but prevents a runtime crash: if b is 0, return 0 instead. · Escribe safe_divide(a, b) que devuelva a / b, pero evite una falla en tiempo de ejecución: si b es 0, devuelve 0 en su lugar.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
average(nums) has two bugs: it divides by the wrong number, and it crashes on an empty list. Fix both, so average([2, 4, 6]) is 4 and · y average([]) is 0. · average(nums) tiene dos errores: divide por un número incorrecto y falla con una lista vacía. Corrige ambos, de modo que average([2, 4, 6]) sea · mar 4 y average([]) sea · mar 0.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.