Fixing Python Syntax Errors with Practical Examples
Table of Contents
Key takeaways
Python stops immediately if it finds a syntax error during parsing.
Python releases starting with 3.10 point to the bracket that was never closed and often add a hint like “Perhaps you forgot a comma?”.
Editors and linters flag these mistakes as you type, and formatters like Black refuse to run on code that doesn’t parse.
A syntax error means Python can’t parse the code, so nothing runs, not even the lines before the error. This guide shows how to read a Python error message, then walks through the most common syntax errors with the broken code, the exact message, and the fix for each.
What is a syntax error in Python?
When you write code, Python expects it to follow the grammar rules of the language, and a syntax error happens when you break them. Python raises it while parsing the file, before any code runs. You will also frequently see IndentationError and TabError, which are both specific types of SyntaxError.
| Type | When it appears | Example |
|---|---|---|
| Syntax error | During parsing, before the code runs | Missing a colon after a function definition |
| Runtime error | While the program runs and an operation fails | Dividing a number by zero (ZeroDivisionError) |
| Logic error | After successful execution, but with the wrong output | Using addition instead of subtraction in a math formula |
How to read a Python syntax error message
When a syntax error stops a script, the traceback shows the file name and line number, repeats the broken line, marks the spot with carets (^), and ends with the error type and message. Here, the carets point at print, because the colon after while True is missing:
File "scraper.py", line 4
while True print("Scraping...")
^^^^^
SyntaxError: invalid syntaxThe caret marks where the parser finally gave up, but the actual mistake is often earlier in the code. For example, a missing comma at the end of one line is reported on the next line, as in the missing commas example below.
Newer Python versions provide much better guidance: Python 3.10 introduced suggestions like “Perhaps you forgot a comma?” and Python 3.14 adds hints like “Did you mean 'while'?”.
Python syntax error examples and how to fix them
Each example shows the broken code, the exact error message, and the fixed code. The messages come from Python 3.15.2; Python 3.11, 3.12 and 3.13 print the same ones.
Missing colon
def fetch_proxy(url)
return requests.get(url).textSyntaxError: expected ':'def fetch_proxy(url):
return requests.get(url).textPython needs a colon to open blocks for functions, loops, and conditional statements. It is easy to miss this punctuation mark at the end of a long line. Python 3.10 and newer clearly tell you when one is missing.
Unclosed brackets and quotes
headers = {'User-Agent': 'Mozilla/5.0'
response = requests.get(url, headers=headers)SyntaxError: '{' was never closedheaders = {'User-Agent': 'Mozilla/5.0'}
response = requests.get(url, headers=headers)When you define dictionaries or lists, Python looks for the closing character. If it hits the end of the file or a new statement first, newer Python versions warn you about the exact unclosed bracket. Older versions used to point to the next line, causing unnecessary confusion.
Unclosed quotes are reported on the line where the string starts: print("Scraping...) gives SyntaxError: unterminated string literal (detected at line 1).
Missing commas
proxies = {
'http': 'http://10.10.1.10:3128'
'https': 'http://10.10.1.10:1080'
}SyntaxError: invalid syntaxproxies = {
'http': 'http://10.10.1.10:3128',
'https': 'http://10.10.1.10:1080'
}Dictionaries and lists need commas between items, including the proxies dictionary you pass to Python Requests. Here, Python joins the two strings into one and stops at the next colon, so it reports invalid syntax on line 3. In a call such as requests.get(url proxies=proxies), Python 3.10 and newer add “Perhaps you forgot a comma?”.
In a list of strings, a missing comma raises no error at all: Python merges the two items into one string, so a proxy or URL list quietly loses an item.
Misspelled keywords and invalid variable names
1st_proxy = "192.168.1.1"
class = "Elite"
wihle True:
passSyntaxError: invalid decimal literalprimary_proxy = "192.168.1.1"
proxy_class = "Elite"
while True:
passPython stops at the first error, so you only get the error message for line 1: variable names cannot start with numbers. Python reserves certain keywords, so using class as a variable name breaks the parser too. A typo like wihle also gives invalid syntax, and Python 3.14 can add “Did you mean 'while'?”.
Using = instead of ==
if response.status_code = 200:
print("Success")SyntaxError: cannot assign to attribute here. Maybe you meant '==' instead of '='?if response.status_code == 200:
print("Success")A single equals sign assigns a value, but a double equals sign checks for equality. Mixing them up is an incorrect usage that breaks conditional statements. Python 3.10 suggests the correct operator directly in the traceback.
Indentation errors
def parse_data(html):
soup = BeautifulSoup(html, 'html.parser')
return soup.titleIndentationError: expected an indented block after function definition on line 1def parse_data(html):
soup = BeautifulSoup(html, 'html.parser')
return soup.titlePython uses indentation to define code blocks. Misaligned code blocks or mixing tabs and spaces will trigger an IndentationError or TabError. This often happens when you paste code snippets from the web into your script.
Invalid characters in copied code
proxy_url = “http://portal.anyip.io:1080”SyntaxError: invalid character '“' (U+201C)proxy_url = "http://portal.anyip.io:1080"Blogs often use formatting that changes standard straight quotes into curly typographical quotes, and some pages put non-breaking spaces between words. Python rejects both outside strings and comments, so pasted code fails at once. A non-breaking space gives SyntaxError: invalid non-printable character U+00A0.
Code written for a different Python version
print "Connection successful"
match status:
case 200: passSyntaxError: Missing parentheses in call to 'print'. Did you mean print(...)?print("Connection successful")
match status:
case 200: passRunning older Python 2 scripts on Python 3 triggers an error because print is now a function that requires parentheses. Similarly, match and case need Python 3.10 or newer, and the := operator needs 3.8, so older parsers reject them. The fixed code runs on 3.10 and newer; on an older interpreter, upgrade or rewrite the block with if and elif.
How to fix a syntax error in Python: step by step
Follow these steps to find and fix syntax errors quickly:
Check the file name, line number, and caret position in the error message.
Look at the flagged line and the one right above it. A missing comma at the end of a line, for example, is reported on the next one.
Make sure all your brackets, braces, and quotes match.
Review your recent edits for simple typos; git diff shows exactly what changed since your last commit.
Run python --version to confirm your current environment supports the syntax you are using.
To check a file for syntax errors without running it, use python -m py_compile script.py in your terminal.
Can you catch a SyntaxError with try/except?
You cannot catch a syntax error in your main script because Python stops during the parsing stage before any code actually runs. You can only catch one if your program evaluates dynamic code on the fly using eval, exec, or compile, or when importing a broken module.
try:
eval("requests.get(url")
except SyntaxError:
print("Caught a broken expression")How to prevent Python syntax errors
Modern editors and IDEs like VS Code or PyCharm highlight syntax errors in real time before you even run the script. You can also use linters like Ruff, Pylint, or Flake8 to flag syntax errors along with style issues before you run the code.
Since the Black formatter refuses to format code it cannot parse, running it is basically a quick syntax check. For team projects, pre-commit hooks are standard practice to prevent developers from committing broken code to the repository.
Finally, stick to a consistent 4-space indentation per PEP 8 to avoid unpredictable whitespace issues.
Conclusion
Read the error message first, treat the caret as a starting point, and check the line above it. Let your editor, a linter, or python -m py_compile catch syntax errors before you run the code. Once the script parses, add a retry strategy for the failed requests that no syntax check can catch.
Frequently Asked Questions
How do I fix a syntax error in Python?
Check the traceback for the file name and line number, look for missing punctuation like unclosed brackets or missing commas, and fix the typo.
What is a syntax error in Python?
It happens when your code breaks the grammar rules of Python, which stops the Python interpreter from parsing the file, so none of the script runs.
What is an example of a syntax error?
For anyone learning Python, missing a colon at the end of an if statement or function definition is one of the most common syntax errors.
How to resolve a syntax error?
Fix your indentation, ensure all brackets and quotes are closed, and check that you spelled Python keywords correctly.
How do I check Python code for syntax errors without running it?
Run python -m py_compile script.py in your terminal. This parses the code and reports errors without actually executing the program. If the file is valid, it prints nothing and saves a .pyc file in __pycache__.
Read more
Python Web Scraping Tutorial: Step-by-Step Guide
Learn Python web scraping step by step. Use Requests and BeautifulSoup to extract website data, parse HTML, and build your first web scraper with examples.
How to customize Your User-Agent with Python Requests
Learn how to update and rotate user-agents in Python Requests to avoid detection and improve scraping efficiency.
How to use proxies with the Python Requests module?
Follow this guide to master Python Requests for web scraping, from basic requests to advanced configuration
:format(webp))
:format(webp))