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

Fix invalid syntax in Python

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 . You’ll receive a 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:

python
x = 5if x = 5:    print(x)# Expected result:#   File "<python-input-0>", line 3#     if x = 5:#        ^^^^^# SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of # '='?

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:

plaintext
  File "example.py", line 4    if item_cost <= bank_balance

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, else

  • for, while

  • def

  • try, except

  • match, 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:

python
bank_balance = 100item_cost = 20if item_cost <= bank_balance    print("Affordable")    bank_balance = bank_balance - item_cost# Expected result:#   File "<python-input-1>", line 4#     if item_cost <= bank_balance#                                 ^# SyntaxError: expected ':'

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 , 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:

python
drinks = ["milk", "juice", "water"print(drinks)# Expected result:#   File "<python-input-2>", line 1#     drinks = ["milk", "juice", "water"#              ^# SyntaxError: '[' was never closed

You’ll also receive an error if you mistakenly pair the bracket with a parenthesis:

python
drinks = ["milk", "juice", "water")print(drinks)# Expected result:#   File "<python-input-3>", line 1#     drinks = ["milk", "juice", "water")#                                       ^# SyntaxError: closing parenthesis ')' does not match opening 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 :

  • Single quotes, '...'

  • Double quotes, "..."

  • Triple quotes, '''...''' or """..."""

It’s easy to miss quotes. Here’s what that could look like:

python
message = "Hello, Kim!print(message)# Expected result:#   File "<python-input-4>", line 1#     message = "Hello, Kim!#               ^# SyntaxError: unterminated string literal (detected at line 1)

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:

python
reply = "She said, "hello" back."print(reply)# Expected result:#   File "<python-input-5>", line 1#     reply = "She said, "hello" back."#                         ^^^^^# SyntaxError: 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 . Use it to set variables to specific values, e.g. x = 2. Two equals signs, ==, however, represent the . 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:

python
user = "guest"while user = "guest":    print("Guest access.")    user = input("Enter username: ")# Expected result:#   File "<python-input-6>", line 3#     while user = "guest":#           ^^^^^^^^^^^^^^# SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of # '='?

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

and 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:

python
prices = [19, 14 39]print(prices)# Expected result:#   File "<python-input-7>", line 1#     prices = [19, 14 39]#                   ^^^^^# SyntaxError: invalid syntax. Perhaps you forgot a comma?

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:

python
2nd_place = "Olivia"print(2nd_place)# Expected result:#   File "<python-input-8>", line 1#     2nd_place = "Olivia"#     ^# SyntaxError: invalid decimal literal

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:

python
class = "Introduction to Python"print(class)# Expected result:#   File "<python-input-9>", line 1#     class = "Introduction to Python"#           ^# SyntaxError: invalid syntax

You can view a list of Python’s reserved keywords by checking kwlist in the built-in keyword module:

python
import keywordprint(keyword.kwlist)# Expected result:# ['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', # 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', # 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', # 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', # 'try', 'while', 'with', 'yield']

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 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:

python
score = 83if score >= 65:print("You passed!")# Expected result:#   File "<python-input-11>", line 4#     print("You passed!")#     ^^^^^# IndentationError: expected an indented block after 'if' statement on # line 3

You’ll get a similar error if you include unexpected indentation:

python
score = 83    print("You passed!")# Expected result:#   File "<python-input-12>", line 2#     print("You passed!")# IndentationError: unexpected indent

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.

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
print "Hello, from Python 2!"

Python 3 switched to the print() function that we know today:

python
print("Hello, from Python 3!")

You’ll get a SyntaxError if you attempt to run the Python 2-style print statement in Python 3:

python
print "Hello, from Python 2!"# Expected result:#   File "<python-input-13>", line 1#     print "Hello, from Python 2!"#     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^# SyntaxError: Missing parentheses in call to 'print'. Did you mean # print(...)?

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 (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 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:

Join the Community

roadmap.sh is the 6th most starred project on GitHub and is visited by hundreds of thousands of developers every month.

Rank  out of 28M!

366K

GitHub Stars

Star us on GitHub
Help us reach #1

+90kevery month

+3.2M

Registered Users

Register yourself
Commit to your growth

+2kevery month

51K

Discord Members

Join on Discord
Join the community

RoadmapsGuidesFAQsYouTube

roadmap.shby@nilbuild

Community created roadmaps, best practices, projects, articles, resources and journeys to help you choose your path and grow in your career.

© roadmap.sh·Terms·Privacy·

ThewNewStack

The top DevOps resource for Kubernetes, cloud-native computing, and large-scale development and deployment.