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:
| Feature | Syntax Error | Run-time Error | Logical Error |
|---|---|---|---|
| When | Before the program runs | While the program runs | After the program finishes |
| Who detects it? | Python interpreter | Python interpreter | You — by checking output |
| Program runs? | No — aborts immediately | Yes, but crashes part-way | Yes, runs to completion |
| Error message? | SyntaxError | An exception name + traceback | None — output is just wrong |
| Fix difficulty | Easy — read the message | Medium — check inputs and conditions | Hardest — 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
| Mistake | Wrong code | Correct code |
|---|---|---|
| Missing colon | if x > 0 | if x > 0: |
| Unmatched bracket / quote | print("hi) | print("hi") |
| Mis-spelt keyword | whilw n > 0: | while n > 0: |
| Wrong indentation | if x: | if x: |
Using = instead of == | if age = 18: | if age == 18: |
| Stray symbol | x = 5;; (in strict parsers) | x = 5 |
| Assignment to a literal | 5 = x | x = 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
| Exception | Raised when… | Trigger example |
|---|---|---|
ZeroDivisionError | Division or modulus by zero | 10 / 0 |
NameError | A variable / function name is not defined | print(x) before x is created |
TypeError | Wrong type for an operation | "hi" + 5 |
ValueError | Correct type but invalid value | int("abc") |
IndexError | Sequence index out of range | [1, 2, 3][5] |
KeyError | Dictionary key not found | {"a": 1}["b"] |
AttributeError | Object has no such attribute / method | "hi".push("x") |
FileNotFoundError | Trying to open a file that doesn't exist | open("no.txt") |
ImportError | A module can't be imported | import nosuchmodule |
RecursionError | Too 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
- Validate input. Never trust what the user types. Convert with
int(input())inside a check. - Check pre-conditions. Before dividing, ensure the denominator is non-zero. Before indexing, check
len(). - Use safe look-ups.
d.get("key", default)never raisesKeyError. - Full exception handling (
try / except / finally) is covered in Class XII. For now, preventing errors is the main strategy.
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
| Pattern | Example | What went wrong |
|---|---|---|
| Wrong operator | perimeter = l * b | Should be 2 * (l + b) — used area formula |
| Operator precedence | a + b + c / 3 | Missing parentheses — divides only c |
| Off-by-one | for i in range(1, 10): | Stops at 9, not 10 — forgot that range(a, b) excludes b |
| Boundary sign flip | if marks > 33: | Student with exactly 33 marks fails — should be >= |
| Wrong variable | total += marks[i-1] | Used stale index — an easy copy-paste error |
| Swapped conditions | if age >= 18 and has_id: (but has_id meant something else) | Code runs, but the business rule is incorrect |
| Integer division surprise | avg = total // n | Used // instead of /, so the decimal part is lost |
12.4.3 How to hunt logical errors — debugging
- Re-read the problem statement. Make sure you understand what the correct answer should be.
- Compute by hand. Pick a small input, work out the expected output with pen and paper, and compare with the program.
- 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
- Test boundary cases. Zero, negative numbers, the smallest and largest valid input, empty strings, empty lists.
- Use a debugger. Professional editors let you pause at any line and inspect every variable step-by-step.
- 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
| Property | Syntax Error | Run-time Error | Logical Error |
|---|---|---|---|
| Detected by | Python interpreter | Python interpreter | You (by checking the output) |
| Detected when | Before program runs | While program runs | After program finishes |
| Program starts? | No | Yes | Yes |
| Program finishes? | No | No — crashes part-way | Yes |
| Error message? | Yes — SyntaxError or IndentationError | Yes — an exception + traceback | No |
| Typical fix | Repair punctuation / keyword | Check inputs / pre-conditions | Re-think the algorithm |
| Difficulty | Low | Medium | High |
| 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 ofdict[key]). Fulltry/excepthandling comes in Class XII. - Golden rule: "Runs without error" ≠ "correct". Always test with multiple inputs including edge cases.