VM-LEARNING /class.xi ·track.cs ·ch-2-6 session: 2026_27
$cd ..

~/Errors in Python

root@vm-learning ~ $ open ch-2-6
UNIT 2 ▪ CHAPTER 6
12
Errors in Python
Syntax Errors · Run-time Errors · Logical Errors · Debugging
An error (also called a bug) is anything in a program that prevents it from running correctly. Errors fall into three broad families depending on when they happen and how visible they are: syntax errors (Python can't even read the code), run-time errors (the code starts but crashes) and logical errors (the code runs without complaint but gives the wrong answer). Learning to recognise, report and repair each kind is half of what "programming" really means.
The life of a Python program — and where each error type strikes:
  • Write the code → spelling and punctuation must be correct: a slip here is a syntax error and Python refuses to run the program.
  • Run the code → Python begins executing, but something unexpected happens (divide by zero, missing file, bad input) — this is a run-time error and the program stops mid-way.
  • Finish the code → it ran all the way through, but the output is wrong: a logical error. Python has no way to know; only you do.
Learning Outcome 1: Classify the three kinds of errors and describe when each occurs.

12.1 The Three Kinds of Errors

Classification of Python errors: Errors in Python (why a program fails) Syntax Error at WRITE time Broken grammar — Python cannot parse the code at all. "It won't even start" e.g., missing :, mis-spelt keyword, bad indentation Run-time Error at RUN time Code looks fine, but something goes wrong while running. "It crashes halfway" e.g., divide by 0, bad index, file missing Logical Error at ANSWER time Program runs fine but gives the wrong answer. "It lies politely" e.g., * instead of +, off-by-one, wrong formula Hardest to spot moves left to right — logical errors are the nastiest because Python itself is happy.
FeatureSyntax ErrorRun-time ErrorLogical Error
WhenBefore the program runsWhile the program runsAfter the program finishes
Who detects it?Python interpreterPython interpreterYou — by checking output
Program runs?No — aborts immediatelyYes, but crashes part-wayYes, runs to completion
Error message?SyntaxErrorAn exception name + tracebackNone — output is just wrong
Fix difficultyEasy — read the messageMedium — check inputs and conditionsHardest — requires thinking
Learning Outcome 2: Recognise and fix syntax errors in Python code.

12.2 Syntax Errors

A syntax error is a violation of the rules of the Python language itself — a mis-placed colon, an unmatched bracket, a keyword typed wrongly, an indentation that doesn't line up. Python's parser stops at the first syntax error and refuses to execute the program until you fix it.

12.2.1 What Python shows you

if marks > 33
    print("Pass")

The missing colon on line 1 produces:

  File "test.py", line 1
    if marks > 33
                ^
SyntaxError: expected ':'

Python tells you the file, the line number, shows the line with a caret (^) pointing near the fault, and names the problem.

12.2.2 Common syntax mistakes

MistakeWrong codeCorrect code
Missing colonif x > 0if x > 0:
Unmatched bracket / quoteprint("hi)print("hi")
Mis-spelt keywordwhilw n > 0:while n > 0:
Wrong indentationif x:
print(x)
if x:
    print(x)
Using = instead of ==if age = 18:if age == 18:
Stray symbolx = 5;; (in strict parsers)x = 5
Assignment to a literal5 = xx = 5

12.2.3 Indentation errors — a special case

Python uses indentation to mark a block. Mixing tabs and spaces, or indenting inconsistently, gives a special syntax error called IndentationError.

if marks >= 33:
print("Pass")          # IndentationError: expected an indented block

if marks >= 33:
    print("Pass")
      print("Well done")   # IndentationError: unexpected indent
Every editor worth using — VS Code, PyCharm, even IDLE — highlights syntax errors with a red squiggle the moment you type them. Watch the red marks and fix as you go.
Learning Outcome 3: Recognise and fix run-time errors (exceptions).

12.3 Run-time Errors (Exceptions)

A run-time error — formally an exception — is one that Python can only detect while the program is executing. The syntax was legal, so Python started running the code; but at some point it hit an operation it couldn't carry out. Execution halts and Python prints a traceback showing where the fault occurred.

12.3.1 Common built-in exceptions

ExceptionRaised when…Trigger example
ZeroDivisionErrorDivision or modulus by zero10 / 0
NameErrorA variable / function name is not definedprint(x) before x is created
TypeErrorWrong type for an operation"hi" + 5
ValueErrorCorrect type but invalid valueint("abc")
IndexErrorSequence index out of range[1, 2, 3][5]
KeyErrorDictionary key not found{"a": 1}["b"]
AttributeErrorObject has no such attribute / method"hi".push("x")
FileNotFoundErrorTrying to open a file that doesn't existopen("no.txt")
ImportErrorA module can't be importedimport nosuchmodule
RecursionErrorToo many nested calls (usually infinite recursion)A function that calls itself forever

12.3.2 Reading a traceback

a = 10
b = 0
print(a / b)

Output:

Traceback (most recent call last):
  File "demo.py", line 3, in <module>
    print(a / b)
ZeroDivisionError: division by zero
How to read a traceback:
  • The last line names the exception and its cause — usually the most useful piece.
  • The lines above show the call chain from top (where execution started) to bottom (where the error occurred).
  • Always read bottom-up when the traceback is long.

12.3.3 How to prevent run-time errors

Learning Outcome 4: Recognise and fix logical errors.

12.4 Logical Errors

A logical error is a mistake in the reasoning of the program — the syntax is legal, the code runs without crashing, but the answer is wrong. Python cannot detect this on its own; only the programmer can.

12.4.1 A classic example

# Calculate the average of three numbers — WRONG
a, b, c = 10, 20, 30
average = a + b + c / 3             # oops — precedence!
print(average)                    # 40.0  — wrong; expected 20.0

The program runs, prints a number, and there is no error message. But the answer 40.0 is wrong — because of operator precedence, only c / 3 got divided. The correct version adds parentheses:

average = (a + b + c) / 3          # 20.0 ✓

12.4.2 Common logical-error patterns

PatternExampleWhat went wrong
Wrong operatorperimeter = l * bShould be 2 * (l + b) — used area formula
Operator precedencea + b + c / 3Missing parentheses — divides only c
Off-by-onefor i in range(1, 10):Stops at 9, not 10 — forgot that range(a, b) excludes b
Boundary sign flipif marks > 33:Student with exactly 33 marks fails — should be >=
Wrong variabletotal += marks[i-1]Used stale index — an easy copy-paste error
Swapped conditionsif age >= 18 and has_id: (but has_id meant something else)Code runs, but the business rule is incorrect
Integer division surpriseavg = total // nUsed // instead of /, so the decimal part is lost

12.4.3 How to hunt logical errors — debugging

  1. Re-read the problem statement. Make sure you understand what the correct answer should be.
  2. Compute by hand. Pick a small input, work out the expected output with pen and paper, and compare with the program.
  3. Add print statements. Print intermediate values — the classic low-tech debugger.
    a, b, c = 10, 20, 30
    print("DEBUG total =", a + b + c)      # 60
    print("DEBUG avg   =", (a + b + c) / 3) # 20.0
  4. Test boundary cases. Zero, negative numbers, the smallest and largest valid input, empty strings, empty lists.
  5. Use a debugger. Professional editors let you pause at any line and inspect every variable step-by-step.
  6. Rubber-duck debugging. Explain your code line by line to a friend — or a rubber duck. You will often spot the error while describing it.
Golden rule. "Can compile" ≠ "works correctly". Never trust code that has only been looked at; always run it with several sample inputs — including edge cases.

12.5 Side-by-side Comparison

PropertySyntax ErrorRun-time ErrorLogical Error
Detected byPython interpreterPython interpreterYou (by checking the output)
Detected whenBefore program runsWhile program runsAfter program finishes
Program starts?NoYesYes
Program finishes?NoNo — crashes part-wayYes
Error message?Yes — SyntaxError or IndentationErrorYes — an exception + tracebackNo
Typical fixRepair punctuation / keywordCheck inputs / pre-conditionsRe-think the algorithm
DifficultyLowMediumHigh
Everyday name"It won't run""It crashed""It gave the wrong answer"

📌 Quick Revision — Chapter 12 at a Glance

  • Error (bug) = anything that prevents a program from running correctly. Three kinds:
  • Syntax error — broken grammar. Python can't even start. Detected before execution. Examples: missing :, unmatched bracket, mis-spelt keyword, wrong indentation, = vs ==.
  • IndentationError is a special syntax error — raised when indentation is missing or inconsistent.
  • Run-time error (exception) — legal syntax, program starts but crashes part-way. Detected during execution. Common exceptions: ZeroDivisionError, NameError, TypeError, ValueError, IndexError, KeyError, AttributeError, FileNotFoundError, ImportError, RecursionError.
  • Traceback — the crash report Python prints. Read the last line for the exception; read the lines above bottom-up for the call chain.
  • Logical error — program runs to completion but output is wrong. Python can never detect it; only you can. Common causes: wrong formula, precedence mistake, off-by-one, boundary sign flip, // vs /, wrong variable.
  • Order of difficulty (easy → hard): Syntax → Run-time → Logical.
  • Debugging techniques: re-read the problem, compute by hand, add print() checkpoints, test edge cases, use a real debugger, rubber-duck the code.
  • Prevent run-time errors: validate input, check pre-conditions, use safe methods (e.g., dict.get() instead of dict[key]). Full try/except handling comes in Class XII.
  • Golden rule: "Runs without error" ≠ "correct". Always test with multiple inputs including edge cases.
🧠Practice Quiz — test yourself on this chapter