Chapter 12 — Errors in Python

Easy-language Notes · Part 1 of 2 (overview · syntax · common exceptions)
REVISION NOTES
Class XI · Computer Science (083)
Sheet 1 (Front)

1. The Three Kinds of Errors

Even experienced programmers make mistakes. Python groups these mistakes into three families. Knowing which type you are facing is the first step to fixing it.

TypeWhen detectedEasy to spot?
Syntax errorBefore the program runsYes — Python refuses to start
Run-time errorWhile the program is runningYes — program crashes with a traceback
Logical errorNever (by Python)Hardest — program runs but answer is wrong
A syntax error is like writing a sentence with bad grammar — the reader stops before reading. A run-time error is like asking someone to divide by zero — they start but quickly give up. A logical error is like swapping "+" and "-" in a maths formula — everything looks fine, the answer is just wrong.

Why this classification matters

  • Each type is found in a different way.
  • Each type is fixed in a different way.
  • Many one-mark exam questions ask "identify the error type" — learn to spot them quickly.
Mantra: "Won't start? → syntax. Crashed? → run-time. Wrong answer? → logic." Apply this 3-step test before you even start fixing.

2. Syntax Errors

A syntax error means the code does not follow Python's grammar rules. Python cannot even begin running your program — it stops at the first bad line and shows SyntaxError.

What Python shows you

  File "prog.py", line 3
    if x > 0
            ^
SyntaxError: expected ':'

Three pieces of useful information: the file, the line number, and a caret pointing at the spot the parser got confused.

Common Syntax Mistakes

Bad codeWhat's wrong
if x > 0Missing colon at end
print "hi"Python 3 needs print()
print("hi"Unclosed parenthesis
if x = 5:Single = in a condition
elseif x > 0:Python uses elif, not elseif
x = "helloUnterminated string

Indentation Errors — a special case

Python uses indentation to mark blocks (no curly braces). Wrong indentation gives IndentationError, which is a sub-type of syntax error.

if x > 0:
print("positive")        # NOT indented
IndentationError: expected an indented block
Stay consistent — pick either spaces or tabs for indentation, but never mix them in the same block. Standard practice is 4 spaces per level.
Syntax errors are caught before any line of code runs. Even print("start") on line 1 won't execute if there is a syntax error on line 5.

3. Run-time Errors — Common Exceptions

A run-time error (also called an exception) happens while the program is running. The syntax was fine, but something illegal occurred at execution time. The program halts with a traceback.

Common Built-in Exceptions

ExceptionWhen it occurs
ZeroDivisionErrorDividing by zero: 10 / 0
TypeErrorWrong type for an operation: "5" + 3
ValueErrorRight type, bad value: int("hello")
NameErrorVariable used before defined: print(z)
IndexErrorList index out of range: L[10] when len = 3
KeyErrorMissing dictionary key: d["xyz"]
AttributeErrorObject has no such method: s.append(1) on string
FileNotFoundErrorOpen a file that does not exist
OverflowErrorNumber too large for its type
A few in action:
a, b = 10, 0
print(a / b)        # ZeroDivisionError

print("5" + 3)       # TypeError

n = int("hello")  # ValueError

print(z)            # NameError (z not defined)

L = [10, 20, 30]
print(L[5])         # IndexError

d = {"a": 1}
print(d["b"])      # KeyError
TypeError means the kinds don't match (string + int). ValueError means the kind is right but the content is wrong (int("hello")). Easy to mix up — remember the difference.

4. Reading a Traceback · Preventing Run-time Errors

Anatomy of a traceback

When a run-time error occurs, Python prints a multi-line message called a traceback. Read it from bottom to top — the last line is the most useful.

Traceback (most recent call last):
  File "prog.py", line 7, in <module>
    avg = total / count
ZeroDivisionError: division by zero
  • File — which file the error happened in.
  • Line — the exact line number.
  • Code — that line shown again, for context.
  • Last line — error type + message. Always read this first.
If your traceback has several "File … line …" entries, the last one is where the error actually happened; the others are the chain of calls that led there.

Preventing Run-time Errors

You can't always avoid them, but a few small habits help a lot:

  • Validate input before using it (check type, range, non-empty).
  • Cast carefully — wrap int(input()) only when you are sure the user will type a number.
  • Check before access — if 0 <= i < len(L): before L[i]; if k in d: before d[k].
  • Avoid divide-by-zero — test the divisor first.
  • Use try / except when an error is expected and recoverable (covered in Class XII).
Defensive division:
a = int(input("a: "))
b = int(input("b: "))
if b == 0:
    print("Cannot divide by zero")
else:
    print(a / b)
The if-check converts a possible ZeroDivisionError crash into a friendly message.

Chapter 12 — Errors in Python

Easy-language Notes · Part 2 of 2 (tracebacks · logical errors · debugging)
REVISION NOTES
Class XI · Computer Science (083)
Sheet 1 (Back)

5. Logical Errors

A logical error means the code runs without crashing, but the answer is wrong. Python cannot detect these — only the human checking the output can.

A Classic Example

Average of three numbers:
a, b, c = 4, 6, 8
avg = a + b + c / 3
print(avg)        # 12.666... (wrong)
# Expected (4+6+8)/3 = 6.0
The bug: precedence. / runs before +, so it computes a + b + (c/3). Fix with brackets: (a + b + c) / 3.

Common Logical-error Patterns

PatternCause
Off-by-onerange(1, n) instead of range(1, n+1)
Missing bracketsWrong operator order, as above
Wrong operator% instead of // (or vice versa)
Wrong condition> when you meant >=
Variable reuseForgot to reset a counter inside a loop
Swapped variablesUsed length where you needed breadth
Off-by-one classic:
total = 0
for i in range(1, 10):
    total += i
print(total)
# Expected: sum of 1..10 = 55
# Got: sum of 1..9 = 45
# Fix: range(1, 11)

How to Hunt Logical Errors — Debugging

  1. Trust nothing. Check the actual output against the expected output.
  2. Add print statements at key points to see variable values.
  3. Run with simple test inputs for which you can easily compute the expected answer by hand.
  4. Try edge cases: 0, negative, very large, empty input, single element.
  5. Read the code line-by-line as if you were the computer; "trace" the values.
  6. Use a debugger (IDLE/VS Code) to step through line by line.
Rubber-duck method: explain your code aloud, line by line, to a small toy or a friend. The act of explaining usually surfaces the bug. Sounds silly, but it works.

6. Side-by-side Comparison

AspectSyntaxRun-timeLogical
Found byPython parserPython interpreterProgrammer
WhenBefore runDuring runAfter run
Program runs?Never startsCrashes mid-wayRuns fully
Output producedNonePartial + tracebackWrong answer
Easy to fixYesSometimesHardest
Exampleif x > 010 / 0a + b / 2
Python messageSyntaxErrorSpecific exceptionNone

Quick Diagnosis Flow

  1. Did Python refuse to start?  →  Syntax error.
  2. Did it crash with a traceback?  →  Run-time error.
  3. Did it run cleanly but give a wrong answer?  →  Logical error.

What an Exam Asks

Most one-mark questions on this topic are of the form "State the type of error in the following code". Use the diagnosis flow above and look at the error message Python would produce:

Error message starts withType
SyntaxError / IndentationErrorSyntax
ZeroDivisionError, TypeError, NameError, ValueError, IndexError, KeyError, AttributeErrorRun-time
(no message — just wrong output)Logical
Logical errors are the most dangerous because Python does not warn you. Always test your program with sample inputs and compare with the expected output before submitting any assignment.
When you finally fix a logical error, write down the test input that caught it — reuse it next time you change the code, so the bug doesn't quietly come back.

Chapter 12 Worksheet — Errors in Python

Total: 50 marks  |  Time: 75 min
Name: Class/Sec: Roll No.: Date:

Section A — Multiple Choice (1 × 10 = 10)

  1. Which type of error is detected before the program runs?
    (a) Syntax(b) Run-time(c) Logical(d) None
  2. Dividing by zero raises:
    (a) ValueError(b) ZeroDivisionError(c) TypeError(d) NameError
  3. int("hello") raises which error?
    (a) TypeError(b) ValueError(c) NameError(d) SyntaxError
  4. An error that Python cannot detect is a:
    (a) Syntax error(b) Run-time error(c) Logical error(d) Indentation error
  5. Accessing a missing key in a dictionary raises:
    (a) IndexError(b) KeyError(c) NameError(d) ValueError
  6. "5" + 3 raises:
    (a) ValueError(b) TypeError(c) SyntaxError(d) NameError
  7. A multi-line crash report is called a:
    (a) backtrace(b) stack(c) traceback(d) log
  8. Wrong indentation gives a:
    (a) ValueError(b) IndentationError(c) TypeError(d) RunError
  9. Using a variable that has not been defined raises:
    (a) NameError(b) ValueError(c) IndexError(d) AttributeError
  10. Which one is NOT a run-time error?
    (a) IndexError(b) KeyError(c) SyntaxError(d) ZeroDivisionError

Section B — Find the Output / Error Type (1 × 8 = 8)

For each snippet, write the output if it runs, or the name of the error it raises.

  1. a = 10
    print(a + b)
    Output / error:
  2. L = [1, 2, 3]
    print(L[3])
    Output / error:
  3. x = 7
    y = 0
    print(x % y)
    Output / error:
  4. d = {"a": 1, "b": 2}
    print(d["c"])
    Output / error:
  5. n = int("3.14")
    print(n)
    Output / error:
  6. a, b, c = 2, 4, 6
    avg = a + b + c / 3
    print(avg)
    Output / error:
  7. s = "hello"
    s.append("!")
    print(s)
    Output / error:
  8. total = 0
    for i in range(1, 5):
        total += i
    print(total)
    Output / error:

Section C — Find the Error (1 × 6 = 6)

Each snippet has exactly one error. Write the line number, the error type (syntax / run-time / logical), and the corrected line.

  1. 1  age = 18
    2  if age >= 18
    3      print("adult")
    Line: Type: Correction:
  2. 1  L = [10, 20, 30]
    2  for i in range(0, 4):
    3      print(L[i])
    Line: Type: Correction:
  3. 1  marks = [88, 76, 92]
    2  total = marks[0] + marks[1] + marks[2]
    3  avg = total / 2
    4  # Wanted: average of 3 marks
    Line: Type: Correction:
  4. 1  num = int(input("N: "))
    2  print("You typed " + num)
    Line: Type: Correction:
  5. 1  s = "Python"
    2  print(s.upper)
    Line: Type: Correction:
  6. 1  d = {"x": 1, "y": 2}
    2  print(d["z"])
    3  # Wanted: print value for x or y
    Line: Type: Correction:

Section D — Short Answer (2 × 5 = 10)

  1. Differentiate between syntax and run-time errors with one example each.
  2. Why is a logical error the hardest to detect? Give one example.
  3. What is a traceback? In which order should you read it?
  4. Differentiate TypeError and ValueError with one example each.
  5. List any four ways to prevent run-time errors in your program.

Chapter 12 Worksheet — (continued)

Sheet 2 (Back)

Section E — Code Tasks (16 marks)

Each program should run without crashing on common inputs and produce a clear output. Use a separate sheet if you need more space.

  1. (2) Write a Python program that reads two integers a and b, then safely prints a / b. If b is 0, print the message "Cannot divide by zero" instead of crashing.
  2. (3) Read a list size n and n integers from the user, then read an index i. Safely print the element at index i, or the message "Index out of range" if the index is invalid.
  3. (3) The following program is meant to print the average of three numbers but contains a logical error. Identify the bug and rewrite the program correctly.
    a, b, c = 4, 6, 8
    avg = a + b + c / 3
    print("Average:", avg)
  4. (2) Read a key from the user. Look it up in the dictionary marks = {"a": 88, "b": 76, "c": 92} and print its value, or print "Key not found" if the key is missing. Use the in operator.
  5. (3) The following loop is meant to compute the sum of integers from 1 to n (inclusive). Identify the off-by-one logical error and write the corrected version.
    n = 10
    total = 0
    for i in range(1, n):
        total += i
    print("Sum:", total)
  6. (3) Identify and label each error in the snippets below as syntax, run-time, or logical. Write the corrected version of each.
    (i)  if x > 0
            print("+")
    
    (ii) print(10 / 0)
    
    (iii) area = length + breadth     # meant l*b