How to Debug Python Code (Beginner Guide)

Debugging means finding out why your Python code is not doing what you expect and then fixing it step by step.

This guide shows a simple process beginners can use to:

  • understand what debugging means
  • find the line causing a problem
  • use print() and traceback messages
  • fix common mistakes without guessing

The goal is not to use advanced tools. The goal is to help you build a repeatable debugging process you can use in any Python program.

Quick way to start debugging

When your code does not work, add simple print() lines to check which lines run and what values your variables contain.

print('Reached here')
print('value of x =', x)
print('type of x =', type(x))

This helps you answer questions like:

  • Did this line run?
  • What value does the variable have right now?
  • Is the variable the type I expect?

If you are new to this, see the print() function explained and the type() function explained.

What this page helps you do

By the end of this page, you should be able to:

  • Understand what debugging means in simple terms
  • Follow a repeatable process to find bugs
  • Use beginner-friendly tools like print() and traceback messages
  • Fix common code problems without guessing

What debugging means

Debugging means finding the cause of a problem in your code.

A bug can be:

  • an error message
  • the wrong output
  • code that runs but does nothing useful

The main goal is to find:

  • the exact line
  • the exact reason

For a general introduction to Python errors, see Python errors and exceptions explained.

Start with the error message

If your program shows an error, start there.

Read the last line first

The last line of the traceback usually tells you the error type.

For example:

numbers = [10, 20, 30]
print(numbers[5])

Output:

Traceback (most recent call last):
  File "main.py", line 2, in <module>
    print(numbers[5])
IndexError: list index out of range

The most important part to notice first is:

IndexError: list index out of range

That tells you what kind of problem happened.

If you get this specific error, see how to fix IndexError: list index out of range.

Check the line number

The traceback also shows the line where Python found the problem.

In the example above, the problem is on line 2:

print(numbers[5])

Now ask:

  • Does this variable contain what I think it contains?
  • Is this index valid?
  • Did I use the right function or value?

Look at the code around that line

Sometimes the real cause starts a few lines earlier.

Example:

name = input("Enter your age: ")
result = name + 5
print(result)

Output:

TypeError: can only concatenate str (not "int") to str

The failing line is:

result = name + 5

But the real cause is above it:

name = input("Enter your age: ")

input() returns a string, not a number. You need to convert it first.

If you see this kind of problem, read how to fix TypeError: unsupported operand type(s) for +.

A simple debugging checklist

Use this checklist every time your code breaks:

  1. Reproduce the problem
    • Run the code again and make sure you can see the same issue.
  2. Read the error message carefully
    • Start with the last line.
    • Then read the traceback above it.
  3. Change one thing at a time
    • If you change many lines at once, you may create new problems.
  4. Check variable values with print()
    • Print important variables before the problem line.
  5. Check data types with type()
    • A value may look right but still be the wrong type.
  6. Make the example smaller
    • Remove unrelated code and focus on the smallest version that still has the bug.
  7. Test after each change
    • This helps you see which change actually fixed the issue.

This process is much better than guessing.

Use print() to inspect your code

print() is one of the easiest debugging tools for beginners.

Use it to:

  • confirm whether a line runs
  • inspect variable values
  • inspect data types
  • compare expected values with actual values

Example: check whether a line runs

print("Program started")

age = 20
print("Age has been set")

if age > 18:
    print("Inside the if block")

print("Program finished")

Output:

Program started
Age has been set
Inside the if block
Program finished

These messages act like checkpoints.

Example: print variable values before a failing line

price = "10"
quantity = 3

print("price =", price)
print("quantity =", quantity)
print("type of price =", type(price))
print("type of quantity =", type(quantity))

total = price * quantity
print(total)

Output:

price = 10
quantity = 3
type of price = <class 'str'>
type of quantity = <class 'int'>
101010

This code does not crash, but the result may be surprising. Because price is a string, "10" * 3 repeats the string.

The printed type helps you spot the problem.

Example: use clear labels

This is better:

x = 7
y = 2
print("x =", x)
print("y =", y)
print("x / y =", x / y)

Than this:

x = 7
y = 2
print(x)
print(y)
print(x / y)

Labels make debugging output much easier to understand.

Check common beginner problems

Many Python bugs come from a few common mistakes.

Wrong indentation

Python uses indentation to define blocks of code.

age = 20

if age > 18:
print("Adult")

This causes an indentation-related error because the print() line should be indented.

Correct version:

age = 20

if age > 18:
    print("Adult")

Using a variable before creating it

print(score)
score = 100

This causes a NameError because score does not exist yet.

Correct version:

score = 100
print(score)

If you see this error, read how to fix NameError: name is not defined.

Mixing strings and numbers

age = "25"
next_year = age + 1
print(next_year)

This fails because "25" is a string.

Correct version:

age = "25"
next_year = int(age) + 1
print(next_year)

Output:

26

Using the wrong list index

colors = ["red", "green", "blue"]
print(colors[3])

This fails because valid indexes are 0, 1, and 2.

Correct version:

colors = ["red", "green", "blue"]
print(colors[2])

Output:

blue

Misspelling variable or function names

message = "Hello"
print(mesage)

mesage and message are different names.

Forgetting to convert input()

age = input("Enter your age: ")
print(age + 1)

This fails because input() returns a string.

Correct version:

age = int(input("Enter your age: "))
print(age + 1)

If you want to handle bad user input safely, see how to use try/except blocks in Python.

When there is no error but the result is wrong

Sometimes your code runs without crashing, but the answer is still wrong. This is called a logic bug.

Check what happens step by step.

numbers = [1, 2, 3, 4]
total = 0

for number in numbers:
    total = number
    print("number =", number, "total =", total)

print("final total =", total)

Output:

number = 1 total = 1
number = 2 total = 2
number = 3 total = 3
number = 4 total = 4
final total = 4

If your goal was to add all numbers, the problem becomes clear: total = number replaces the total each time.

Correct version:

numbers = [1, 2, 3, 4]
total = 0

for number in numbers:
    total = total + number
    print("number =", number, "total =", total)

print("final total =", total)

Output:

number = 1 total = 1
number = 2 total = 3
number = 3 total = 6
number = 4 total = 10
final total = 10

Check loop conditions and if conditions

If a block never runs, print the values being tested.

age = 17
print("age =", age)

if age > 18:
    print("Adult")

Now you can clearly see why "Adult" is not printed.

Test with small sample data

If your program is hard to follow, use a very small example first.

Instead of testing with 1,000 items, test with 2 or 3.

This makes it easier to see where the logic goes wrong.

Compare expected output with actual output

Ask yourself:

  • What result did I expect?
  • What result did I get?
  • At which step do they become different?

That helps you focus on the real problem.

How to make bugs easier to find

You cannot avoid every bug, but you can make them easier to debug.

Write small functions

Small functions are easier to test than one large block of code.

Instead of writing everything together:

name = input("Enter your name: ")
name = name.strip()
name = name.title()
print("Hello", name)

You can separate the work:

def clean_name(text):
    return text.strip().title()

name = input("Enter your name: ")
cleaned = clean_name(name)
print("Hello", cleaned)

Now, if something goes wrong, you can test clean_name() by itself.

Use clear variable names

This is easier to debug:

student_age = 16

Than this:

x = 16

Clear names make your code easier to read and easier to fix.

Test one part at a time

If your program reads a file, processes data, and prints a result, test each part separately.

That way you can find which part is failing.

Keep code simple before adding features

Start with a small working version first.

Then add one feature at a time and test after each change.

When to use a debugger tool later

Beginners do not need to start with advanced tools.

print() debugging is enough for many problems because it helps you learn the core process:

  • observe the problem
  • inspect values
  • test a small change
  • run the code again

Later, you can learn debugger tools in an IDE. These tools let you:

  • pause code while it runs
  • inspect variables
  • step through the program line by line

That can be very helpful, but it works best after you already understand basic debugging.

Common mistakes when debugging

These habits make debugging harder:

  • Not reading the full error message
    • The traceback often tells you exactly where to look.
  • Changing many lines at once
    • If the code starts working, you will not know what fixed it.
  • Assuming a variable has the value you expect
    • Print it and check.
  • Forgetting type conversion after input()
    • input() returns a string.
  • Using data from a file or API without checking its format
    • Print the data and inspect it before using it.
  • Trying to fix code by guessing
    • Use a process instead.

Useful debugging commands

These simple commands are helpful when checking your code:

print(variable)
print(type(variable))
print('checkpoint')
help(function_name)
dir(object_name)

What they do:

  • print(variable) shows the current value
  • print(type(variable)) shows the data type
  • print('checkpoint') confirms a line ran
  • help(function_name) shows built-in help for a function
  • dir(object_name) shows available attributes and methods

Example:

text = "hello"

print(text)
print(type(text))
print(dir(text))

FAQ

What is the easiest way to debug Python code?

Start by reading the error message, then use print() to check which lines run and what values your variables have.

Why is my Python code wrong even without an error?

Your code may have a logic bug. Print intermediate values and compare the actual result with the result you expected.

Should beginners use a debugger or print()?

Start with print() because it is simple and works everywhere. Later, you can learn an IDE debugger.

What should I check first in a traceback?

Check the last line for the error type, then look at the line number and the code around that line.

See also