COMPUTER PROGRAMMING 1 (PYTHON) โ€ข DEBUGGING, TESTING & CODE QUALITY

Error Types โ€” I can distinguish syntax errors, runtime errors, and logic errors and give examples.

Learn to identify the three fundamental categories of programming errors and fix them efficiently.

Historical Context & Motivation

Every programmer, from absolute beginners to seasoned professionals, encounters errors โ€” sometimes called bugs โ€” in their code. The word "bug" itself has a storied history in computing, and the practice of finding and fixing errors has evolved alongside programming languages themselves. Understanding how the computing community learned to classify errors helps you appreciate why we still sort them into three distinct categories today.

1947
The First Literal "Bug"
Grace Hopper's team at Harvard found a moth trapped inside the Mark II computer, coining the popular use of "bug" for a computer malfunction. The term "debugging" soon followed.
1950s
Early Compilers & Syntax Checking
As programming languages like FORTRAN emerged, compilers began automatically checking code structure before execution, creating the first formal category of errors: syntax errors.
1960s
Runtime Errors Gain a Name
Operating systems started catching crashes during program execution โ€” such as division by zero or memory violations โ€” and reporting them as runtime errors distinct from compile-time issues.
1972
Logic Errors & Software Engineering
The growing software crisis highlighted that programs could run without crashing yet still produce wrong results. The concept of logic errors became a central concern in the emerging discipline of software engineering.
1991
Python's Friendly Error Messages
Guido van Rossum released Python, which was designed with readable, descriptive error messages โ€” called tracebacks โ€” making it easier for beginners to identify and fix syntax and runtime errors.

Over decades of programming, the community settled on three broad categories of errors: those the language catches before running your code, those that crash during execution, and those that silently produce incorrect output. The key question this lesson addresses is: how do you tell them apart, and what do you do about each one?

Core Principles & Definitions

Before you can fix a problem, you need to diagnose it correctly. Just as a doctor classifies symptoms before prescribing treatment, a programmer classifies errors before debugging. Python errors fall into three fundamental types, each occurring at a different stage of your program's lifecycle.

1

Syntax Error

A violation of the language's grammar rules. Python detects these before your program runs. Common causes include missing colons, unmatched parentheses, and misspelled keywords.
2

Runtime Error

An error that occurs during program execution, causing the program to crash. The syntax is valid, but an operation fails โ€” for example, dividing by zero or accessing a list index that doesn't exist.
3

Logic Error

The program runs without crashing but produces incorrect results. The code is syntactically valid and doesn't crash, but the algorithm or formula is wrong. These are the hardest to find because Python gives no error message.
โœฆ KEY TAKEAWAY
Think of writing code like baking a cake. A syntax error is like writing "preheat the oevn" โ€” the recipe is unreadable and you can't even start. A runtime error is like discovering mid-recipe that you're out of eggs โ€” the process halts. A logic error is like accidentally using salt instead of sugar โ€” the cake comes out fine, but it tastes terrible. The result is wrong even though you followed every step.

Visual Explanation

This diagram shows the lifecycle of a Python program from writing code through parsing and execution. Syntax errors are caught at the parsing stage, runtime errors crash during execution, and logic errors slip through undetected because the program runs to completion with wrong results.

As the diagram illustrates, each error type corresponds to a different phase of your program's life. When you press "Run," Python first reads (parses) your entire file to check that the grammar is valid. If it finds a broken rule, it stops immediately with a SyntaxError โ€” your code never even starts executing. If the grammar checks out, Python begins executing your code line by line. An instruction that is grammatically correct can still fail at this stage, producing a runtime error like ZeroDivisionError or IndexError. Finally, if every line runs without crashing, you might still get the wrong answer due to a logic error โ€” and Python won't warn you at all.

How Python Detects Each Error Type

Syntax Errors: The Parser's Job

When you run a Python file, the interpreter first converts your source code into an internal representation called an Abstract Syntax Tree (AST). During this process, the parser checks every line against Python's grammar rules. If it encounters something it doesn't understand โ€” like a missing colon after an if statement or mismatched quotes โ€” it raises a SyntaxError and points to the approximate location of the mistake with a caret (^) symbol.

๐Ÿ“‹ Common Syntax Errors in Python
Missing colons after if, for, while, and def statements; unmatched parentheses, brackets, or quotes; incorrect indentation; using = instead of == in comparisons; and misspelling keywords like retrun instead of return.

Runtime Errors: The Executor's Problem

Once the code passes the parser, Python begins running it line by line. A runtime error (also called an exception) occurs when an instruction is grammatically correct but asks the computer to do something impossible or undefined. Python names these errors precisely: a ZeroDivisionError means you tried to divide by zero, a TypeError means you mixed incompatible data types, and a NameError means you used a variable that hasn't been defined. The program halts at the exact line where the error occurs and prints a traceback showing the chain of function calls that led to the crash.

Logic Errors: The Programmer's Blind Spot

A logic error is the sneakiest type because Python provides absolutely no error message. The code is valid, runs to completion, and produces output โ€” but that output is wrong. These errors stem from mistakes in your algorithm or reasoning, such as using the wrong formula, placing a statement inside a loop when it should be outside, or using > when you meant >=. To catch logic errors, you must test your program with known inputs and compare the actual output to the expected output.

โš ๏ธ Why Logic Errors Are the Hardest to Fix
Syntax errors and runtime errors give you an error message and a line number. Logic errors give you nothing โ€” the program looks like it's working perfectly. The only clue is that your output doesn't match what you expected. This is why testing with known inputs and expected outputs is one of the most important habits a programmer can develop.

Detailed Error Classification with Examples

Now that you understand the three categories conceptually, let's look at specific Python error names and code examples for each one. The table below maps common error names to their type and provides a quick code snippet showing what triggers each one.

Common Python errors organized by type
Error TypePython Error NameExample CodeWhat Went Wrong
SyntaxSyntaxErrorif x == 5Missing colon at end of if statement
SyntaxIndentationErrordef greet():\nprint('hi')Body of function not indented
RuntimeZeroDivisionErrorresult = 10 / 0Cannot divide by zero
RuntimeNameErrorprint(mesage)Variable 'mesage' was never defined (typo)
RuntimeIndexErrorlst = [1,2]; lst[5]Index 5 doesn't exist in a 2-element list
RuntimeTypeError'age: ' + 17Cannot concatenate a string and an integer
Logic(No error name)avg = a + b / 2Should be (a + b) / 2 โ€” order of operations
Logic(No error name)if score > 90:Should be >= 90 if 90 qualifies for an A
Side-by-side comparison of the three error types showing when they're detected, whether Python gives an error message, and their relative difficulty to fix.

Notice the pattern in the comparison above: the later an error is caught, the harder it is to fix. Syntax errors are caught immediately with a clear message and caret pointing to the problem. Runtime errors give you a traceback, but the real cause might not be on the exact line that crashed. Logic errors provide no error message at all, meaning you have to rely on testing and careful reasoning to track them down.

Worked Example: Diagnosing Errors in a Program

Let's walk through a short Python program that is supposed to calculate the average of three test scores. The original code has one error of each type. We'll identify, classify, and fix each one.

Finding and Fixing All Three Error Types
1
Step 1 โ€” Read the Original CodeHere is the buggy program: score1 = 85 score2 = 90 score3 = int(input("Enter score 3: ") average = score1 + score2 + score3 / 3 print("Average: " + average) Our goal is to find all three error types before running the program.
2
Step 2 โ€” Identify the Syntax ErrorLook at line 3: score3 = int(input("Enter score 3: "). Count the parentheses โ€” there are three opening parentheses but only two closing ones. Python's parser will catch this and report a SyntaxError before the program starts.
Fix: Add the missing closing parenthesis โ†’ score3 = int(input("Enter score 3: "))
3
Step 3 โ€” Identify the Runtime ErrorAfter fixing the syntax error, the program will run. Look at line 5: print("Average: " + average). The variable average is a number (float or int), and you cannot concatenate a string with a number using + in Python. This will raise a TypeError when the program reaches that line.
Fix: Convert the number to a string โ†’ print("Average: " + str(average))
4
Step 4 โ€” Identify the Logic ErrorAfter fixing both previous errors, the program runs and prints a result. But look at line 4: average = score1 + score2 + score3 / 3. Due to Python's order of operations, score3 / 3 is calculated first, and then added to score1 and score2. If all three scores are 90, this gives 90 + 90 + 30 = 210 instead of the correct average of 90. Python won't complain โ€” it just gives the wrong answer.
Fix: Add parentheses โ†’ average = (score1 + score2 + score3) / 3
5
Step 5 โ€” Verify the Corrected ProgramThe corrected program: score1 = 85 score2 = 90 score3 = int(input("Enter score 3: ")) average = (score1 + score2 + score3) / 3 print("Average: " + str(average)) Test it with score3 = 95: the average should be (85 + 90 + 95) / 3 = 90.0. If the program outputs 90.0, all three bugs are fixed.
Expected output: Average: 90.0 โœ…

Comparing Error Types: Strengths & Strategies

Each error type requires a different debugging strategy. Knowing which approach to use saves time and reduces frustration. The table below summarizes what to look for and how to fix each type.

Debugging strategy comparison for each error type
FeatureSyntax ErrorRuntime ErrorLogic Error
Detected byPython's parserPython's executorYou (the programmer)
WhenBefore any code runsWhen the faulty line executesWhen you check output
Error message?Yes โ€” SyntaxError with caretYes โ€” named exception with tracebackNo message at all
Fix strategyRead the error message, check the indicated line and the line above itRead the traceback from bottom to top, add input validation or type conversionTest with known inputs, use print statements or a debugger, trace through code by hand
PreventionUse an IDE with syntax highlighting and lintingValidate user input, use try/except blocksPlan your algorithm before coding, write test cases
โœฆ KEY TAKEAWAY
Think of debugging like troubleshooting a car. A syntax error is like turning the key and the car won't start โ€” the dashboard immediately tells you what's wrong. A runtime error is like driving down the road and hitting a pothole that blows a tire โ€” you were moving, but something specific stopped you. A logic error is like driving smoothly to the wrong destination โ€” the car works perfectly, but you took a wrong turn. The best debugging strategy depends on which scenario you're dealing with.

Connection to Advanced Error Handling

Understanding the three error types is just the beginning. As you advance in Python, you'll learn techniques specifically designed to handle and even prevent each type. The table below previews how beginners and more advanced programmers deal with errors differently.

From beginner error fixing to professional error handling
ConceptWhat You Learn NowWhat Comes Next
Syntax ErrorsRead the SyntaxError message and fix the typoUse linters (like pylint or flake8) that catch errors in real time as you type
Runtime ErrorsRead the traceback and fix the crashUse try/except blocks to gracefully handle errors, write custom exception classes
Logic ErrorsUse print statements to check intermediate valuesWrite unit tests with frameworks like unittest or pytest to automatically verify correctness
Overall ApproachFix errors one at a time as they appearPractice test-driven development (TDD) โ€” write tests before code to prevent logic errors

In more advanced courses, you'll discover that Python's exception handling system with try, except, finally, and raise gives you powerful tools to anticipate runtime errors and respond gracefully instead of crashing. You'll also learn to write automated tests โ€” small programs that check whether your main program produces the right output for dozens or hundreds of input cases. These skills build directly on the error classification you're learning today.

Practice Problems

PROBLEM 1 โ€” CONCEPTUAL
A student runs their Python program and sees no error message, but the program outputs 50 when the correct answer should be 25. What type of error is this, and why doesn't Python catch it?
PROBLEM 2 โ€” BASIC CALCULATION
Classify each of the following as a syntax error, runtime error, or logic error: (a) print("Hello World" (b) x = int("abc") (c) A program that should calculate the area of a circle using area = 2 * 3.14 * r instead of area = 3.14 * r ** 2
PROBLEM 3 โ€” INTERMEDIATE
The following program is supposed to ask the user for a number and print whether it is positive, negative, or zero. Identify all errors, classify each one, and provide corrected code. num = input("Enter a number: ") if num > 0 print("Positive") elif num = 0: print("Zero") else: print("Negative")
PROBLEM 4 โ€” APPLIED
A teacher writes a program to calculate the class average from a list of grades. The program runs without error messages but consistently reports an average that is too low. The code is: grades = [88, 92, 75, 95, 80] total = 0 for g in grades: total = total + g average = total / len(grades) print(average) Explain what type of error this is, why the result is wrong, and how to fix it.
PROBLEM 5 โ€” CRITICAL THINKING
Is it possible for a single line of code to be free of syntax errors, free of runtime errors in some cases but cause a runtime error in other cases? Give a concrete Python example and explain the conditions that determine whether the error occurs. Then explain how this fact connects to the importance of testing with multiple inputs.

Lesson Summary

Python programs can contain three types of errors. Syntax errors violate the language's grammar rules and are caught by the parser before any code runs โ€” they produce a SyntaxError message with a caret pointing to the problem. Runtime errors (exceptions) occur during execution when a valid instruction encounters an impossible operation, such as dividing by zero or accessing a nonexistent list index. Python names these precisely (ZeroDivisionError, TypeError, IndexError) and provides a traceback showing the chain of calls.

Logic errors are the trickiest: the program runs without crashing but produces incorrect results because the algorithm or formula is wrong. Python provides no error message for logic errors, so the only way to detect them is to test with known inputs and compare actual output to expected output. Remember: the later an error is caught in the program lifecycle, the harder it is to fix. Building the habit of reading error messages carefully, using print() statements for debugging, and testing with multiple inputs will make you a much more effective programmer.

Varsity Tutors โ€ข Computer Programming 1 (Python) โ€ข Error Types โ€” I can distinguish syntax errors, runtime errors, and logic errors and give examples.