depuración Python Thonny Python Tutor VS Code

Depuración en Python — cómo encontrar errores con 3 herramientas esenciales

Depuración en Python es una de las habilidades más importantes que nadie te enseña directamente en primero. Sabes escribir código, pero cuando algo falla, y siempre falla, no sabes por dónde empezar a buscar.

En este artículo te explico cómo depurar en Python usando las tres herramientas que más uso: Thonny, Python Tutor y el depurador de VS Code. Además veremos los tres tipos de errores que más aparecen en FP1 y cómo identificarlos rápido.

¿Qué es depurar?

Depurar (del inglés debug) es el proceso de encontrar y corregir errores en tu código. Un bug es cualquier cosa que hace que tu programa no funcione como esperas, puede ser un error que rompe el programa o un resultado incorrecto silencioso que pasa desapercibido.

Hay tres tipos de errores que te encontrarás constantemente en FP1:

Errores de sintaxis (SyntaxError)

El código está mal escrito y Python no puede ni ejecutarlo. Son los más fáciles de encontrar porque Python te dice exactamente en qué línea está el problema:

# SyntaxError típico — falta el : al final del if
if x > 5
    print("mayor")
```
```
SyntaxError: expected ':'

Errores de tipo (TypeError, ValueError)

El código tiene buena sintaxis pero en algún punto intentas hacer algo con un tipo de dato incorrecto:

# TypeError — sumar texto con número
edad = input("Edad: ")
nueva_edad = edad + 1    # input() devuelve str, no int
```
```
TypeError: can only concatenate str (not "int") to str

Errores silenciosos

El más peligroso. El programa ejecuta sin errores pero el resultado es incorrecto. Python no te avisa porque técnicamente no hay ningún error, simplemente la lógica está mal:

# Error silencioso — falta paréntesis en la media
media = nota1 + nota2 + nota3 / 3    # divide solo nota3 entre 3
# Resultado incorrecto pero sin error

Para este tercer tipo es donde la depuración es más importante.

Herramienta 1 — Thonny

Thonny es el editor que usamos en clase en FP1. Tiene un depurador visual muy intuitivo que es perfecto para empezar. Para depurar en Thonny:

Abre tu archivo en Thonny y en vez de darle al botón de play normal (F5), dale al botón de «Debug» — el icono del insecto. Esto ejecuta el programa paso a paso.

depurar en python usando Thonny

Con el programa en modo debug tienes estos controles:

Step Over (F6) — ejecuta la línea actual y pasa a la siguiente. Úsalo para avanzar línea por línea viendo cómo cambian las variables.

Step Into (F7) — entra dentro de una función para ver qué hace por dentro.

Step Out (F8) — sale de la función actual y vuelve al código principal.

Lo más útil de Thonny es el panel de Variables en la parte derecha (ábrelo desde el menú de «Visualizar»), muestra en tiempo real el nombre, tipo y valor de cada variable mientras el programa avanza. Es la forma más visual de ver exactamente qué está pasando.

Herramienta 2 — Python Tutor

Ya hemos mencionado Python Tutor en artículos anteriores (enlaza al artículo de variables) porque es perfecta para visualizar cómo Python gestiona la memoria. Para depurar con ella:

Ve a pythontutor.com, pega tu código y dale a «Visualize Execution». Verás el código con una flecha que indica qué línea se ejecuta ahora mismo, y a la derecha todos los objetos en memoria con sus valores.

Es especialmente útil para entender errores silenciosos, puedes ver exactamente qué valor tiene cada variable en cada momento y detectar dónde la lógica se tuerce.

Herramienta 3 — El depurador de VS Code

Yo no sabía que VS Code tenía depurador integrado hasta hace poco, y es muy potente. Para usarlo:

Abre tu archivo .py en VS Code y haz clic en el número de línea donde quieres que el programa se pause, aparecerá un punto rojo llamado breakpoint.

Luego pulsa F5 o ve a Ejecutar → Iniciar depuración. El programa se ejecutará hasta llegar al breakpoint y se pausará ahí.

En el panel izquierdo verás:

Variables — todas las variables activas con sus valores actuales.

Watch — puedes añadir expresiones para monitorizar. Por ejemplo nota1 + nota2 te muestra el resultado de esa suma en tiempo real.

Call Stack — muestra en qué función estás en cada momento.

Los controles de depuración son iguales que en Thonny:
F5 → Continuar hasta el siguiente breakpoint
F10 → Step Over (siguiente línea)
F11 → Step Into (entrar en función)
F12 → Step Out (salir de función)

Mi flujo de depuración en la práctica

Después de usar estas herramientas en FP1, este es el orden que sigo cuando algo falla:

Paso 1 — Leo el error completo. Si Python da un error, lo leo entero, especialmente la última línea que dice el tipo de error y el número de línea. No busco en Google antes de leer el mensaje completo.

Paso 2 — Busco el error en Google. Copio el mensaje de error exacto y lo busco. El 99% de los errores de primero ya están resueltos en Stack Overflow.

Paso 3 — Añado prints para rastrear. Si no hay error pero el resultado es incorrecto, añado print() temporales para ver el valor de las variables en puntos clave:

nota1 = 7.5
nota2 = 8.0
nota3 = 6.0

print(f"Debug: nota1={nota1}, nota2={nota2}, nota3={nota3}")
media = nota1 + nota2 + nota3 / 3
print(f"Debug: media={media}")  # aquí ves el error

Paso 4 — Uso Python Tutor o Thonny. Si con los prints no encuentro el problema, abro Python Tutor para ejecutar paso a paso y ver exactamente dónde la lógica falla.

Paso 5 — Uso el depurador de VS Code. Para programas más largos o complejos, el depurador de VS Code con breakpoints es más cómodo que Python Tutor.

Los mensajes de error más comunes en FP1

Guarda esta tabla, te ahorrará tiempo buscando en Google:

# SyntaxError: expected ':'
# → Te falta el : al final de if, for, while o def

# IndentationError: unexpected indent
# → La indentación no es correcta — revisa los espacios

# TypeError: can only concatenate str (not "int") to str
# → Estás sumando texto con número — convierte con int() o float()

# ValueError: invalid literal for int() with base 10
# → Intentas convertir texto no numérico a número
# → Ejemplo: int("hola") da este error

# NameError: name 'x' is not defined
# → Usas una variable antes de declararla o con nombre incorrecto

# ZeroDivisionError: division by zero
# → Estás dividiendo entre 0 — añade una comprobación if b != 0

Resumen — cuándo usar cada herramienta

  • SyntaxError o TypeError → lee el mensaje de error + Google
  • Error silencioso en código corto → Python Tutor
  • Error silencioso en código largo → depurador de VS Code con breakpoints
  • Aprendiendo un concepto nuevo → Thonny en modo debug paso a paso
  • Primera línea de defensa siempreprint() estratégicos

En el próximo tema, estructuras de control, la depuración se vuelve más importante porque los errores silenciosos en if/elif/else y bucles son más difíciles de detectar.


Python debugging — how to find errors with 3 essential tools

Python debugging is one of the most important skills nobody teaches you directly in first year. You know how to write code, but when something goes wrong, you don’t know where to start looking. This article covers how to debug Python using the three tools I actually use: Thonny, Python Tutor and VS Code. Plus the three error types that appear most in FP1.

What is debugging?

Debugging is finding and fixing errors in your code. A bug is anything that makes your program behave unexpectedly, either crashing with an error or silently producing wrong results.

Three types of errors you’ll encounter constantly:

Syntax errors (SyntaxError)

The code is written incorrectly and Python can’t even run it. Easiest to find — Python tells you exactly which line:

# Missing : at end of if
if x > 5
    print("greater")
# SyntaxError: expected ':'

Type errors (TypeError, ValueError)

Correct syntax but wrong data type at runtime:

age = input("Age: ")
new_age = age + 1    # input() returns str, not int
# TypeError: can only concatenate str (not "int") to str

Silent errors

The most dangerous. Program runs without errors but produces wrong results:

# Missing parentheses in average
average = grade1 + grade2 + grade3 / 3  # only divides grade3 by 3
# No error — just wrong answer

Tool 1 — Thonny

Thonny is the editor we use in FP1 class. Instead of the normal play button (F5), click the Debug button (the bug icon). This runs the program step by step.

Controls:

  • F6 — Step Over: execute current line, move to next
  • F7 — Step Into: enter a function
  • F8 — Step Out: exit current function

The Variables panel on the right shows every variable’s name, type and value in real time as the program advances.

Tool 2 — Python Tutor

Go to pythontutor.com, paste your code and click «Visualize Execution». You’ll see an arrow pointing to the current line and all objects in memory on the right.

For input() — replace with fixed values while debugging:

# Instead of:
grade1 = float(input("Grade 1: "))
# Use:
grade1 = 7.5

Tool 3 — VS Code debugger

I didn’t know VS Code had a built-in debugger until recently — and it’s very powerful. Click a line number to add a breakpoint (red dot), then press F5 to start debugging. The program pauses at the breakpoint.

Left panel shows:

  • Variables — all active variables with current values
  • Watch — monitor custom expressions like grade1 + grade2
  • Call Stack — shows which function you’re currently in

Controls: F5 continue, F10 step over, F11 step into, F12 step out.

My debugging workflow

  1. Read the full error message — especially the last line with error type and line number
  2. Google the exact error — copy and paste it. 99% of FP1 errors are solved on Stack Overflow
  3. Add strategic prints — to track variable values at key points
  4. Use Python Tutor — for short code with silent errors
  5. Use VS Code debugger — for longer programs with breakpoints

Most common error messages in FP1

# SyntaxError: expected ':'
# → Missing : after if, for, while or def

# IndentationError: unexpected indent
# → Wrong indentation — check your spaces

# TypeError: can only concatenate str (not "int") to str
# → Mixing text and number — convert with int() or float()

# ValueError: invalid literal for int() with base 10
# → Trying to convert non-numeric text to number

# NameError: name 'x' is not defined
# → Using variable before declaring it

# ZeroDivisionError: division by zero
# → Add if b != 0 check before dividing

Summary — when to use each tool

  • SyntaxError / TypeError → read the message + Google
  • Silent error in short code → Python Tutor
  • Silent error in long code → VS Code debugger with breakpoints
  • Learning a new concept → Thonny step-by-step debug mode
  • Always first → strategic print() statements

Publicaciones Similares

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *