SkarpSkarp

Chapter 10 of 11

Finding and Fixing Problems: Errors, Debugging, and Good Habits

Every programmer, beginner or expert, runs into errors—what matters is how quickly you can understand and fix them. You’ll learn to read Python’s error messages, avoid common pitfalls, and adopt simple habits that make your code more reliable.

15 min readen

Step 1: Why Errors Are Normal (And Useful)

Errors Are Normal

Every programmer, beginner or expert, runs into errors all the time. Errors are not a sign you are bad at coding; they are clues that show what your program is really doing.

What You Will Learn

You will learn to: tell syntax vs runtime errors, read a traceback to find the problem line, use print statements to debug, and write a basic try/except to handle simple errors.

Think of Errors as Signs

Think of errors like traffic signs. At first they look confusing. Once you learn what each sign means, you can react quickly and safely instead of feeling lost.

Step 2: Two Main Types of Errors

Two Main Error Types

Python errors you see most often fall into two groups: 1) syntax errors and 2) runtime errors (also called exceptions). Knowing which one you have is the first step.

Syntax Errors

A syntax error means Python cannot even read this code. It is like a sentence with broken grammar. Python stops before running and shows a SyntaxError message.

Runtime Errors

A runtime error happens while the program is running. The code is valid Python, but something goes wrong, like dividing by zero. Python calls these errors exceptions.

Step 3: Seeing Syntax vs Runtime Errors

Example: Syntax Error

In a syntax error, Python cannot read the code. A missing parenthesis in input("How old are you?" causes a SyntaxError, and the program stops before any print runs.

Example: Runtime Error

In a runtime error, the code is valid Python, but fails when running. For example, dividing 10 by a user-entered number can cause ZeroDivisionError or ValueError depending on the input.

Key Question

When you see an error, first ask: Is this a SyntaxError, or some other error type? That tells you if the problem is in how the code is written or in what happens when it runs.

Step 4: How to Read a Traceback

What Is a Traceback?

A traceback is Python’s error report. It shows the file and line number where the error happened, the line of code that failed, and the error type with a short message.

Read From the Bottom

When you see a traceback, start from the bottom line. That line gives the error type, like ZeroDivisionError, and a short message, such as division by zero.

Find the Problem Line

Then look one line above the bottom. It shows the exact line of code that crashed, with the file name and line number so you can go straight there to fix it.

Step 5: Spot the Problem Line (Thought Exercise)

Look at this traceback and answer the questions in your head or on paper.

```text

Traceback (most recent call last):

File "calculator.py", line 5, in <module>

total = price * quantity

NameError: name 'price' is not defined

```

Questions:

  1. What is the error type?
  2. What is the short message?
  3. On which file and line number did the error happen?
  4. Which variable seems to be the problem?
  5. How might you fix it?

Possible answers (check yourself):

  1. Error type: `NameError`
  2. Message: `name 'price' is not defined`
  3. File and line: `calculator.py`, line 5
  4. Problem variable: `price`
  5. Fix idea: Make sure `price` is created before line 5, spelled exactly the same, for example:

```python

price = 10

quantity = 3

total = price * quantity

```

Step 6: Print Debugging – Your First Debug Tool

One of the simplest and most powerful ways to debug is to print out values while your program runs. This is called print debugging.

Imagine this code:

```python

score = int(input("Enter your score: "))

if score > 90:

grade = "A"

elif score > 80:

grade = "B"

else:

grade = "C"

print("Your grade is:", grade)

```

Suppose you think the grade is wrong for some inputs. Add print statements to see what is happening:

```python

score = int(input("Enter your score: "))

print("DEBUG: score is", score) # debug print

if score > 90:

grade = "A"

elif score > 80:

grade = "B"

else:

grade = "C"

print("DEBUG: grade is", grade) # debug print

print("Your grade is:", grade)

```

When you run the program, the `DEBUG:` lines help you check:

  • Did `score` have the value you expected?
  • Did `grade` change the way you expected?

You can remove or comment out these debug prints when you are done:

```python

print("DEBUG: score is", score)

```

Step 7: Intro to try/except – Handling Simple Errors

Why try/except?

Sometimes you expect that an error might happen and you want to handle it nicely instead of crashing. Python uses try/except blocks for this situation.

The Pattern

In a try block, you put code that might fail. In an except block, you say what to do if a specific error type happens, like ValueError or ZeroDivisionError.

Example: Safer Input

Wrapping `age = int(input(...))` in try/except ValueError lets you show a friendly message if the user types text instead of a number, instead of showing a scary traceback.

Step 8: Quick Check – Errors and Tracebacks

Test your understanding of basic error types and tracebacks.

You run a Python program and see this message at the bottom of the output: ZeroDivisionError: division by zero What kind of problem is this?

  1. A syntax error: Python could not read the code at all
  2. A runtime error (exception): something went wrong while the code was running
  3. Just a warning: the program finished normally
Show Answer

Answer: B) A runtime error (exception): something went wrong while the code was running

A ZeroDivisionError is a runtime error (an exception). The code is valid Python, but dividing by zero is not allowed when the program runs.

Step 9: Quick Check – try/except Basics

Test your understanding of try/except.

Which is the best reason to use a try/except block around `int(input("Enter a number: "))`?

  1. To make the program run faster
  2. To prevent any kind of error from ever happening
  3. To handle the case where the user types something that is not a valid integer
Show Answer

Answer: C) To handle the case where the user types something that is not a valid integer

A try/except around `int(input(...))` lets you catch a ValueError when the user types something that is not a valid integer, and respond with a friendly message instead of crashing.

Step 10: Review Key Terms

Flip through these cards to review the main ideas from this module.

Syntax error
An error where Python cannot read the code at all because the "grammar" is wrong. Detected before the program starts running, usually shown as SyntaxError.
Runtime error (exception)
An error that happens while the program is running, even though the code is valid Python. Examples: ZeroDivisionError, ValueError, NameError.
Traceback
Python’s error report. It shows the file and line number where the error happened, the code line, and the error type with a short message.
Debugging
The process of finding and fixing problems (bugs) in your code. Often involves reading tracebacks, using print statements, and testing small pieces of code.
Print debugging
A simple debugging method where you add print statements to show variable values and program flow, helping you see what is really happening.
try/except block
Python structure used to handle expected errors. Code that might fail goes in try; the except block defines what to do if a specific error type occurs.
ValueError
A common exception raised when a function gets a value of the right type but wrong form, such as int("hello"). Often handled when working with user input.

Key Terms

NameError
An exception raised when code uses a variable name that has not been defined.
debugging
The process of finding, understanding, and fixing errors (bugs) in code.
exception
Python’s term for a runtime error. Each exception has a type, such as ZeroDivisionError or ValueError, and usually a short message.
traceback
The multi-line error message Python prints when an exception is not handled. It shows where the error happened and what type it was.
ValueError
A common Python exception raised when a function receives a value of the correct type but an invalid form, such as converting non-numeric text to an int.
try/except
A Python structure used to run code that might fail (try) and then catch and handle specific exceptions (except) instead of crashing.
syntax error
An error that occurs when Python cannot understand the code because it breaks the language rules, such as missing parentheses or colons.
runtime error
An error that occurs while the program is running, even though the code is syntactically correct. In Python, these are called exceptions.
print debugging
A simple debugging method where you add temporary print statements to display variable values or program steps.
ZeroDivisionError
An exception raised when code attempts to divide a number by zero.

Finished reading?

Test your understanding with a custom practice exam on this chapter.

Test yourself