Skip to content

SyntaxError: invalid syntax

Error message

                SyntaxError: invalid syntax
              

Quick summary

Python can't parse your code — there's a missing colon, parenthesis, or wrong keyword somewhere on the reported line.

Why this happens

  • Missing colon after if, for, while, or def

  • Unclosed parenthesis, bracket, or string

  • Used a keyword incorrectly (e.g., elif without if)

Minimal example

✗ Broken code
if x == 5
    print("yes")
✓ Fixed code
if x == 5:
    print("yes")

Python if statements require a colon after the condition — without it, the parser reports invalid syntax.

How to diagnose

  • Read the line number and the caret (^) pointer in the error

  • Check the reported line AND the line before it

  • Look for missing colons, parentheses, or quotes

How to fix

  • Add the missing colon, parenthesis, or quote

  • Fix the incorrect keyword or operator

  • Run python -m py_compile <file> to check for syntax errors

How to prevent

  • Use an IDE with real-time syntax checking (VS Code, PyCharm)

  • Run a linter like flake8 or pylint to catch issues early

Related Resources

Related Glossary

Related Lessons

Related Practice

← Back to language