Common errors
When your code breaks, Python prints a traceback — a block of red text that looks intimidating but is actually a map straight to the problem. Learn to read it and most bugs become obvious.
Read the traceback from the bottom up
The last line is the most important. It tells you the error type and a short message. The lines above it show where in your code the error happened.
Start at the bottom: NameError: name 'total' is not defined. That tells you exactly what's wrong. The line above shows the offending code and its line number. Always read the last line first.
NameError — a name Python doesn't know
A NameError means you used a name that hasn't been defined — usually a typo or a variable you forgot to create:
The fix: check your spelling and make sure the variable is defined before you use it.
TypeError — the wrong type for the operation
A TypeError happens when you try to do something with a value that its type doesn't support — like adding a string and a number:
You can't glue a string and an int together with +. The fix is to convert the number, or use an f-string:
SyntaxError — Python can't even read the code
A SyntaxError means the code itself is written incorrectly, so Python can't run it at all. Common causes: a missing colon, an unclosed quote or bracket, or wrong indentation:
The fix here is the missing : after the condition:
No comments yet. Add the first comment to start the discussion.