Start Here

Reading An Error Message

Reading An Error Message

The first time you get red text it feels like you have broken something. You have not.

An error message is the most useful output your program produces. It says what went wrong and where.

Every programmer sees errors daily — twenty years in, still daily. The difference is that an experienced one reads the message and fixes it in ten seconds.

Read it from the bottom

Traceback (most recent call last):
  File "agent.py", line 12, in <module>
    print(students[10])
IndexError: list index out of range

The last line is the answer. A type on the left, plain English on the right. Ninety per cent of the time that one line is enough.

The line above it is where it happened. Everything under Traceback is how you got there — ignore it while your code is one cell.

The five that happen in the first class

Not theoretical. Every one of these came up live.

1. Capital P

Print("hello")
NameError: name 'Print' is not defined

Python is case-sensitive. It is print.

2. A stray space

def add(a, b):
    return a + b

 print(add(4, 5))
IndentationError: unexpected indent

One space, and Python thinks the line is inside a block.

3. Nothing happened at all

def add(a, b):
    return a + b

No error. No output. Nothing.

Those lines define the function; they do not run it — see Defining, Calling And Blocks. Call it:

print(add(4, 5))

If you got silence where you expected an answer, check you actually called the thing.

4. A missing colon

if number > 5
    print("bigger")
SyntaxError: expected ':'

Every if, for, while, def and class line ends with a colon.

5. Text that looks like a number

age = "34"
print(age + 1)
TypeError: can only concatenate str (not "int") to str

The quotes make it text. Use int(age) + 1.

The rest, briefly

MessageMeansFix
NameErrorthat name does not existcheck spelling; check you ran the cell
IndexErrorthat position does not existcheck len(my_list)
KeyErrorthat key is not in the dictionaryuse .get("key", default)
AttributeErrorno such methodcheck spelling and the object's type
ModuleNotFoundErrorlibrary not installedpip install thelibrary

When SyntaxError blames an innocent line

scores = [90, 85, 72
print("done")

It blames line 2. Line 2 is fine. The missing ] is on line 1 — Python kept reading and gave up on the next line.

When a SyntaxError makes no sense, look at the line above.

NameError for something you can see

You wrote the variable, it is right there on screen, and Python insists it does not exist.

You never ran that cell. Runtime → Restart and run all fixes it.

When stuck

Two minutes, in this order:

  • Read the last line, out loud if it helps
  • Go to the line number
  • If that line looks fine, check the line above
  • Print what you actually have: print(type(x), x)
  • Paste the last line only into an AI chat
  • Still stuck after five minutes — ask, and paste the error and the code

"It is not working" cannot be answered. The error plus five lines can be, in a minute.

The habit worth building

Do not change code at random until the red goes away. That occasionally works and teaches you nothing.

Say a sentence instead: "KeyError on 'city' means the dictionary has no city key, which means the response is shaped differently from what I assumed."

Once you can say it, the fix is obvious.

This is exactly the habit that makes AI-written code safe to use. When the AI's code breaks — and it will — you are the one reading the message.

Practise this

  • Cause all five first-class errors on purpose. Fix each.
  • Define a function, get nothing, then call it.
  • Make a KeyError, then fix it with .get() and with an if.
  • Take an error you do not understand and say in one sentence what you think it means, before looking it up.

Try It Yourself

Copy this into a new Colab notebook and run it. Nothing to install.

example.py
1# The five errors that actually happened in the first class, on purpose.
2# Every one of these is normal. Nothing is damaged.
3
4def show(label, code):
5 print(f"--- {label} ---")
6 try:
7 exec(code, {})
8 except Exception as e:
9 print(f"{type(e).__name__}: {e}")
10 print()
11
12
13# 1. Capital P. Python is case-sensitive.
14show("1. Print with a capital P", 'Print("hello")')
15
16# 2. A stray space before a line that should be at the outer level.
17show("2. A stray space", 'def add(a, b):\n return a + b\n\n print(add(4, 5))')
18
19# 3. A missing colon.
20show("3. Missing colon", 'number = 10\nif number > 5\n print("bigger")')
21
22# 4. Text that looks like a number.
23show("4. Text that looks like a number", 'age = "34"\nprint(age + 1)')
24
25# 5. Nothing happened at all - and this one raises NO error.
26print("--- 5. Defined but never called ---")
27def add(a, b):
28 return a + b
29print("(no output above - the function was defined, not called)")
30print("now calling it:", add(4, 5))
31print()
32
33
34# The others you meet soon:
35show("NameError", 'name = "Priya"\nprint(nmae)')
36show("IndexError", 'students = ["Amit", "Sara"]\nprint(students[10])')
37show("KeyError", 'member = {"name": "Priya"}\nprint(member["city"])')
38show("ValueError", 'print(int("abc"))')
39show("AttributeError", 'print("hello".uppercase())')
40
41
42# A SyntaxError that blames the wrong line:
43print("--- SyntaxError pointing at an innocent line ---")
44try:
45 exec('scores = [90, 85, 72\nprint("done")')
46except SyntaxError as e:
47 print(f"SyntaxError on line {e.lineno}: {e.msg}")
48 print(" -> line 2 is fine. The real problem is the missing ] on line 1.")
49 print(" -> when a SyntaxError makes no sense, look at the line ABOVE.")
50print()
51
52
53# The fix for KeyError, two ways:
54member = {"name": "Priya"}
55print("safe with .get():", member.get("city", "unknown"))
56if "city" in member:
57 print(member["city"])
58else:
59 print("safe with 'in' : no city")
60print()
61
62# And the habit: say a sentence before you change anything.
63print('"It says KeyError on city, which means the dictionary has no key')
64print(' called city, which means the response is shaped differently from')
65print(' what I assumed." Once you can say that, the fix is obvious.')