1. What syntax means
Syntax is the grammar of a language. In English, “dog the barked” uses real words in the wrong shape, and you still roughly understand it. Python does not do roughly. It reads your line strictly, left to right, and if the shape is wrong it stops and refuses to run any of your program.
That sounds harsh, but it's the friendlier choice. Imagine if Python guessed what you meant and got it wrong halfway through marking a test. A refusal at the start is much easier to fix than a wrong answer at the end.
2. Read the error message, it's a clue
Beginners see red text and panic. Programmers read it. Every Python error hands you three things:
- A line number. Where Python noticed the problem.
- A type.
SyntaxError,IndentationError,NameError, and so on. - A short description, often with a
^pointing at the exact spot.
One catch worth knowing: the line number is where Python gave up, not always where you went wrong. Leave a bracket open and Python keeps reading on, hoping to find it, so the mistake can be a line or two above the number it prints. If a line looks perfect, check the one above it.
Python has got much better at this lately. Miss a closing bracket and it now says '(' was never closed and points back at the right line; get a name slightly wrong and it even guesses what you meant: NameError: name 'highscore' is not defined. Did you mean: 'high_score'? Read the whole message, not just the red.
3. The five usual suspects
Almost every beginner error is one of these. Learn the five and you can debug most of your own code.
| Mistake | Looks like | Python says |
|---|---|---|
| Missing colon | if age > 12 |
SyntaxError: expected ':' |
| Missing indentation | a line after : starting at the far left |
IndentationError: expected an indented block |
| Name does not match | user_name made, username used |
NameError: name 'username' is not defined |
| One = instead of two | if age = 13: |
SyntaxError: invalid syntax |
| Bracket or quote left open | print("hello |
SyntaxError: unterminated string / was never closed |
Two habits that catch nearly all of them. Count your brackets: every ( needs a ), every " needs a partner. And read the colon line and the line under it together: colon, then indent, every single time.
4. The game: hunt the broken line
Five short programs, each with exactly one mistake. Click the line you think is wrong. You get one guess each, and the answer is explained either way.
Ready to make it harder? Tick Hard mode above. Spotting the line is then only half of it: you have to retype that line correctly before the point counts, which means actually knowing the repair, not just recognising the shape. Still out of 5, just a tougher route to it.