Fix "Invalid Syntax" in Python (8 Common Causes)

Abstractly, you can think of your code as a conversation with Python that includes instructions. Most of the time your conversation will flow smoothly and follow a logical progression, but every once in a while, Python just won’t be able to understand you. On those occasions, you may have invalid syntax. You’ll need to diagnose the source of your miscommunication and correct the issue to get back on the same page with Python.
In this article, we’ll cover invalid syntax through Python’s SyntaxError, including common causes and solutions. We’ll take you through reading an error message and other debugging tips to make sure your Python syntax doesn’t get lost in translation.
Overview of the SyntaxError Exception
Just like a natural language such as English, Python has grammatical rules, which are broadly called syntax. You’ll receive a SyntaxError exception when you violate one of these rules. When the Python interpreter encounters invalid syntax during the parsing stage, it recognizes that it can’t parse your code and raises an error before the affected code executes.
You’ll see several more syntax error examples coming up, but here’s a quick snippet demonstrating what you could experience:
You’ll be alerted to your incorrect syntax, and newer Python versions even offer a helpful suggestion.
How to Read a Python Error Message with a Line Number
Before diving into some of the common causes of a SyntaxError with invalid syntax, it’s worth taking a moment to understand how to read an error message. Python developers rely on these messages because they serve as valuable clues to locate and fix any issues with your code.
Here’s an example error message:
In the first line of the error message, you’ll see the .py file name (e.g. example.py) or input (e.g. <python-input-0>) if you’re working within an interactive environment. Next, you’ll see the line number where Python detected a syntax issue. That’s your starting point for debugging, but keep in mind the line number doesn’t always tell you where the actual error began.
Python then provides you with relevant source code that could contain your bug in the second line of the error message. That’s followed by caret (^) highlighting to flag locations associated with your syntax problem. Once again, the carets are generally pretty accurate but not guaranteed to point to your exact error.
Finally, you’ll find your exception type (e.g. SyntaxError, KeyError) along with a helpful message describing your error (e.g. expected ':') in the last line of the message.
Use each of these pieces as clues to diagnose and fix errors in your Python code. As a best practice, check both the indicated line and previous lines since the problem may have started further up. Now let’s put these clues to use by exploring several common causes of Python SyntaxErrors.
Common Causes of a SyntaxError
Not all SyntaxError exceptions come with “invalid syntax” messages, but all SyntaxError: invalid syntax responses are SyntaxErrors. We’ll review some of the most common causes of syntax errors in this section and note where Python typically includes “invalid syntax” in the error message.
Missing Colon
Python requires a colon, :, after statements that begin an indented block, such as:
if,elif,elsefor,whiledeftry,exceptmatch,case
Forgetting this colon is not only a common mistake, but also a typical reason for Python to raise a SyntaxError. Here’s what a missing colon looks like:
New versions of Python will likely identify the missing colon, but older implementations may still list SyntaxError: invalid syntax. Check for missing colons and add them before indented statement blocks to correct this mistake.
Missing Parentheses, Brackets, or Braces
You’ll find parentheses, brackets, and braces throughout Python code for lists, dictionaries, function calls, and other places. Just be sure that if you open one of these delimiters, you also close it. Missing or mismatched delimiter pairs in Python is another typical cause of a SyntaxError.
If you try to create a list in Python, but forget the ending bracket of your list, you’ll get an error:
You’ll also receive an error if you mistakenly pair the bracket with a parenthesis:
Here again, you may see SyntaxError: invalid syntax when working with older Python versions.
This problem becomes particularly difficult when working with highly nested code structures. Try checking for matching pairs using an editor with delimiter highlighting and work from the innermost pair outward.
Missing Quotes
Similar to missing or mismatched delimiters, you’ll receive a SyntaxError if you have missing quotes. You’ll also need to verify the style of your quote mark matches its partner when creating a string literal:
Single quotes,
'...'Double quotes,
"..."Triple quotes,
'''...'''or"""..."""
It’s easy to miss quotes. Here’s what that could look like:
Unclosed strings cause Python to raise a SyntaxError. Also pay close attention to quotation marks within string literals. For the following example, the inner " prematurely closes the surrounding string, leaving hello outside the string and resulting in invalid syntax:
Quotes within strings require alternative quote types ('She said, "hello" back.') or escaping ("She said, \"hello\" back.").
= versus ==
In Python, a single equals sign, =, is the assignment operator. Use it to set variables to specific values, e.g. x = 2. Two equals signs, ==, however, represent the equality comparison operator. This compares two values and returns True or False, depending on their equivalence.
If you accidentally use a single equals sign when comparing items, you’ll receive a SyntaxError alerting you to your invalid syntax:
You saw this same error earlier when we first introduced SyntaxError: invalid syntax. To fix the issue, switch to two equals signs in the while statement comparison (user == "guest").
This problem commonly pops up in if, elif, and while conditions as well as in Boolean expressions, so check those places if you’re having issues with = versus ==. Also keep in mind that a single equals sign, =, is valid Python, but you should use it for assignment rather than comparison.
Missing Comma between List/Dictionary Items
Lists and dictionaries require commas to separate collection elements, e.g. [1, 2, 3] and {"California": "West", "Ohio": "Midwest"}, respectively. Forgetting a comma between items is yet another common mistake that can lead to a SyntaxError:
You’ll also see errors like this one if you miss a comma between elements in dictionaries, tuples, sets, or arguments in a function call. Check collections and arguments carefully to avoid associated SyntaxErrors.
Invalid Variable Names and Reserved Keywords
Python variables commonly use letters, numbers, and underscores, but they cannot begin with a digit. Python may raise a SyntaxError if you violate variable naming rules:
Try spelling out numerical words (second_place) and removing forbidden characters to fix variable names that aren’t valid.
Python also keeps a stock of reserved keywords that you may not use as ordinary variable names, e.g. if, for, while, class, True, and None. Attempting to do so can also result in a SyntaxError:
You can view a list of Python’s reserved keywords by checking kwlist in the built-in keyword module:
To bypass raising a SyntaxError, you should not use any of these keywords as variable names.
Incorrect Indentation and Tab Errors
Unlike some other programming languages, Python relies on indentation to define code blocks. You must indent code after if, for, while, def, and so on for Python to consider the code part of your statement; likewise, you’ll also have incorrect indentation if you add indents to lines that don’t require them.
You may receive an IndentationError, which is a subclass of SyntaxError, if you forget this indentation:
You’ll get a similar error if you include unexpected indentation:
If you happen to see a TabError, that’s also within the SyntaxError hierarchy. PEP 8 recommends four spaces per indentation level and prefers spaces over tabs. You can also configure many editors to automatically insert four spaces when you press the Tab key.
print Statement (Invalid Syntax Python 2 versus 3)
Python 3 debuted near the end of 2008, while Python 2 reached its end-of-life in 2020. You likely won’t need to deal with details related to this version update today unless you’re reviewing legacy code or older tutorials. That said, one of the most visible changes for developers moving from Python 2 to Python 3 was the syntax of the print statement.
In Python 2, print statements looked like this:
Python 3 switched to the print() function that we know today:
You’ll get a SyntaxError if you attempt to run the Python 2-style print statement in Python 3:
Use the Python 3 print() function to fix SyntaxErrors like this.
Quick Lookup Table to Fix SyntaxError
We provided you with many different reasons for SyntaxErrors. Here’s a condensed reference table to summarize those Python issues and to correct them with valid syntax:
Error/Clue | Likely Cause | Where to Check | Fix |
|---|---|---|---|
expected ':' | Missing colon | End of if, for, def, etc. | Add : |
'[' was never closed | Missing delimiter | Matching [], (), {} | Close delimiter |
unterminated string literal | Missing quote | Opening/closing quotes | Add matching quote |
Maybe you meant '==' | = used for comparison | Conditions/Boolean expressions | Replace with == |
Perhaps you forgot a comma? | Missing comma separator | Collections/arguments | Add comma |
invalid decimal literal | Invalid variable name | Variables beginning with a digit | Rename variable |
IndentationError | Incorrect indentation | Code blocks | Add/remove indentation |
Missing parentheses in call to 'print' | Python 2 print syntax | Legacy print statement | Use print() |
Debugging Tips and Tools
With the large number of possible SyntaxErrors, you’ll want to adopt some clever methods for debugging. Whether you choose to manually debug your Python code or to rely on tools like linters and IDEs, here are some tips to keep in mind.
Manually Debugging Invalid Syntax
You’ll want to thoroughly read any error message Python provides to diagnose syntax issues. Remember to use the line number referenced in the message as a starting place, but check all the lines preceding as needed to find where the error occurred. Delimiters, quotes, and indentations notoriously cause a hefty number of coding errors, so also double-check those when faced with invalid syntax.
You may run into issues when copying and pasting code. Retype any suspicious characters that you’ve copied from elsewhere. Additionally, you may find it helpful to isolate bugs by reducing your code down to the smallest failing section. Knowing where to find the problem serves as your first step in error correction.
Preventing Errors with Linters and IDEs
If you choose to use an integrated development environment (IDE) or code editor such as Visual Studio Code, PyCharm, or Spyder, you’ll gain access to popular automated syntax checking tools. These tools can help with syntax highlighting to detect problems as you type your code. Think of it like an automated spell check when writing a document. The IDE or editor can alert you to missing delimiters or incorrect indentation in real time before you run your code and face a SyntaxError.
Furthermore, you can process your code with a linter like Ruff, Pylint, or Flake8. You can often incorporate a linter into your code editor to have it analyze your code without executing it. The linter can pick up on syntax issues, undefined variables, PEP 8 issues, and a whole host of other problems.
Wrapping Up
SyntaxError exceptions, including problems with invalid syntax, occur when you violate one of Python’s grammar rules and it can’t parse your code. As you’re learning Python, you’ll find there are many different causes of syntax issues such as forgetting a colon after a function name, missing a parenthesis, using = instead of ==, including incorrect indentation, or assigning invalid names to variables. Utilize Python’s helpful error messages to diagnose and eventually fix any syntax problems that come up, and consider leveraging an IDE or linter for built-in tools that notify you of potential errors as you type.
Think you can spot and fix invalid syntax errors in Python? Interact with the AI Tutor to test out your skills starting from this prompt:
- The or Operator in Python: Complete Guide with Examples
- Python reduce(): The Complete Guide (With Examples)
- Master Python Filter: Syntax, Examples, and Best Practices
- Python Max Int: Understanding Arbitrary Precision Integers
- Python KeyError Exceptions: Causes and Fixes Explained
- Python Null (None): Guide to Missing Values and NoneType
- Python Backend Development: Build Your First API
- Python Backend Frameworks: How to Choose the Right One
- Python Return Multiple Values: 4 Methods & Examples
- Python Multiline Strings: The Complete Guide
Kimberly Fessel