Fetch real-time data from 100+ websites,No development or maintenance required.
Over 100 million real residential IPs from genuine users across 190+ countries.
SCRAPING SOLUTIONS
Get accurate and in real-time results sourced from Google, Bing, and more.
With 120+ prebuilt and custom scrapers ready for any use case.
No blocks, no CAPTCHAs—unlock websites seamlessly at scale.
Execute scripts in stealth browsers with full rendering and automation
PROXY INFRASTRUCTURE
Over 100 million real residential IPs from genuine users across 190+ countries.
Reliable mobile data extraction, powered by real 4G/5G mobile IPs.
For time-sensitive tasks, utilize residential IPs with unlimited bandwidth.
Fast and cost-efficient IPs optimized for large-scale scraping.
SCRAPING SOLUTIONS
PROXY INFRASTRUCTURE
DATA FEEDS
Full details on all features, parameters, and integrations, with code samples in every major language.
LEARNING HUB
ALL LOCATIONS Proxy Locations
TOOLS
RESELLER
Get up to 50%
Contact sales:partner@thordata.com
Products $/GB
Fetch real-time data from 100+ websites,No development or maintenance required.
Get real-time results from search engines. Only pay for successful responses.
Execute scripts in stealth browsers with full rendering and automation.
Bid farewell to CAPTCHAs and anti-scraping, scrape public sites effortlessly.
Dataset Marketplace Pre-collected data from 100+ domains.
Over 100 million real residential IPs from genuine users across 190+ countries.
Reliable mobile data extraction, powered by real 4G/5G mobile IPs.
For time-sensitive tasks, utilize residential IPs with unlimited bandwidth.
Fast and cost-efficient IPs optimized for large-scale scraping.
Data for AI $/GB
Pricing $0/GB
Docs $/GB
Full details on all features, parameters, and integrations, with code samples in every major language.
Resource $/GB
EN $/GB
产品 $/GB
AI数据 $/GB
定价 $0/GB
产品文档 $/GB
资源 $/GB
简体中文 $/GB
Python Syntax Errors: Common Mistakes and How to Fix Them
Content by Kael Odin
Python syntax errors are among the most common issues developers face, especially when learning the language or working on complex projects. Unlike runtime errors that occur during execution, syntax errors prevent your code from running at all—Python’s interpreter catches them during the parsing phase before any code execution begins.
This 2026 edition of the guide provides a comprehensive, up-to-date resource for understanding, debugging, and preventing Python syntax errors. Whether you’re a beginner encountering your first SyntaxError or an experienced developer troubleshooting complex code in production, this guide focuses on realistic examples and modern best practices that match how Python is used in web scraping, data engineering, and API workloads today.
Whether you’re building web scrapers, working with APIs, or automating tasks, understanding Python syntax errors is fundamental. This guide uses practical examples that you’ll encounter in real projects—from handling HTTP headers and parsing JSON responses to managing complex data structures. If you’re working on web scraping projects and need help beyond syntax errors, check out our web scraping solutions or explore our open-source examples for production-ready code patterns.
If you prefer learning by running code, this tutorial’s examples are organized in a small repository. Once the repo is published, you can browse each snippet via the “View on GitHub” button inside code blocks.
# Validate examples
python tests/test_examples.py
# Check syntax under src/
python tools/syntax_checker.py src/ --verbose
Syntax errors occur when Python’s parser cannot understand the structure of your code. They violate Python’s grammatical rules and must be fixed before the code can execute.
Key Characteristics:
SyntaxError exception| Error Type | When Detected | Example | Impact |
|---|---|---|---|
| Syntax Error | During parsing | Missing colon : |
Code won’t run |
| Runtime Error | During execution | Division by zero | Program crashes |
| Logical Error | Never (by Python) | Wrong algorithm | Wrong output |
Python error messages are designed to help you locate and fix issues. Understanding their structure is crucial for efficient debugging.
When Python encounters a syntax error, it provides:
# File: example.py
prices = {"price1": 9.99, "price2": 13.48 "price3": 10.99}
Error Output:
File "example.py", line 1
prices = {"price1": 9.99, "price2": 13.48 "price3": 10.99}
^
SyntaxError: invalid syntax. Perhaps you forgot a comma?
Breaking it down:
example.py – The file containing the error13.48 and "price3" – the likely issue locationPython uses indentation to define code blocks. This is one of Python’s most distinctive features and a common source of errors.
def process_data():
data = [1, 2, 3]
for item in data:
print(item) # Missing indentation
Error:
IndentationError: expected an indented block after 'for' statement
Solution:
def process_data():
data = [1, 2, 3]
for item in data:
print(item) # Properly indented
Best Practice: Use 4 spaces consistently. Configure your editor to convert tabs to spaces.
Colons (:) are required after function definitions, class definitions, and control flow statements.
defdef greet(name) # Missing colon
return f"Hello, {name}!"
Error:
SyntaxError: expected ':'
Solution:
def greet(name): # Colon added
return f"Hello, {name}!"
| Statement | Required Colon |
|---|---|
def function_name(): | ✅ Yes |
class ClassName: | ✅ Yes |
if condition: | ✅ Yes |
elif condition: | ✅ Yes |
else: | ✅ Yes |
for item in iterable: | ✅ Yes |
while condition: | ✅ Yes |
try: | ✅ Yes |
except Exception: | ✅ Yes |
finally: | ✅ Yes |
with context_manager: | ✅ Yes |
match value: (Python 3.10+) | ✅ Yes |
Python strings can use single quotes ('), double quotes ("), or triple quotes (""" / '''). The opening and closing quotes must match.
message = "Hello, world'
text = 'This is a "string"
url = 'https://example.com"
Fix: Close the string with the same quote type you used to open it.
message = "Hello, world"
text = 'This is a string'
url = "https://example.com"
If your string contains quotes, either escape them or use a different quote type.
print("He said "Hello" to me")
print('It's a beautiful day')
print("He said \\"Hello\\" to me")
print('It\\'s a beautiful day')
SyntaxError: unterminated string literal, scan upward for a quote that never closes.
Missing commas or unclosed brackets often trigger a generic SyntaxError: invalid syntax. If the caret (^) points somewhere that looks fine, the actual mistake is often just before it.
fruits = ['apple' 'banana' 'cherry']
prices = {"apple": 1.50 "banana": 0.75 "cherry": 2.00}
fruits = ['apple', 'banana', 'cherry']
prices = {"apple": 1.50, "banana": 0.75, "cherry": 2.00}
Many syntax errors come from using = where Python expects == (comparison), : (dict key/value), or simply a valid assignment target.
price_1 = 200.99
price_2 = 200.98
compare = (price_1 = price_2)
print(compare)
price_1 = 200.99
price_2 = 200.98
compare = (price_1 == price_2)
print(compare)
Reserved keywords like class, def, pass, and return cannot be used as variable names.
class = "Python 101"
pass = "password123"
course = "Python 101"
password = "password123"
Variable names must start with a letter or underscore and can only contain letters, numbers, and underscores.
2response = requests.get(url)
response2 = requests.get(url)
Newer Python features are great, but they introduce new syntax rules. Two frequent sources of errors are pattern matching (Python 3.10+) and type hints.
match status:
case "success"
print("Operation succeeded")
match status:
case "success":
print("Operation succeeded")
When you’re stuck, use tooling to narrow down where the parser got confused.
ast.parse() catches syntax errors without executing code.python -m py_compile your_file.py validates syntax quickly.Modern linters catch syntax errors before runtime. Popular tools include pylint for comprehensive code analysis, flake8 for style guide enforcement, and black for automatic code formatting. When working with Python projects that involve web scraping or API development, tools like these become essential for maintaining code quality.
For example, if you’re building web scrapers with Python, using a linter helps catch syntax errors early—especially important when dealing with complex parsing logic or API integrations. You can find practical examples of Python web scraping projects in our Python SDK repository, which demonstrates proper syntax usage in real-world scenarios.
This guide includes a syntax checker tool you can run against a file or folder. You can find it in the tools directory of our GitHub repository:
python tools/syntax_checker.py src/ --verbose
python tools/syntax_checker.py src/punctuation_errors/example_2_fixed.py
| Error Pattern | Example | Fix |
|---|---|---|
| Missing colon | if x > 5 |
if x > 5: |
| Missing comma | [1, 2 3] |
[1, 2, 3] |
| Unclosed quote | "Hello |
"Hello" |
| Wrong indentation | print(x) (inconsistent) |
print(x) (4 spaces) |
Using = for comparison |
if x = 5: |
if x == 5: |
| Reserved keyword | class = "Python" |
course = "Python" |
| Variable starts with number | 2items = [] |
items2 = [] |
| Error Message | Common Cause | Quick Fix |
|---|---|---|
expected ':' |
Missing colon | Add : after statement |
invalid syntax |
Various | Check punctuation, quotes, operators |
unterminated string literal |
Unclosed quote | Close the string with matching quote |
expected an indented block |
Missing indentation | Indent the code block |
cannot assign to literal |
Using = on literal |
Use variable name instead |
invalid decimal literal |
Variable starts with number | Rename variable |
All code examples from this guide, along with the syntax checker tool and test suite, are available in our GitHub repository. The repository includes 50+ examples covering all 8 error categories, making it easy to copy, test, and learn from real-world scenarios.
Black (recommended) automatically formats your code and fixes many indentation and style issues:
pip install black
black your_script.py
For larger projects, consider integrating formatters into your CI/CD pipeline. If you’re working with web scraping projects, maintaining consistent code style becomes even more important when collaborating with teams or integrating with APIs. You can see examples of well-formatted Python code in our proxy examples repository.
The PEP 8 style guide provides Python’s official coding conventions. Key points include:
Following PEP 8 helps prevent many common syntax errors, especially those related to indentation and naming. The official Python documentation provides detailed guidance on SyntaxError exceptions and IndentationError if you need to dive deeper into error handling.
Python syntax errors can be frustrating, but with a clear understanding of how error messages work and the common patterns we’ve covered, you can debug them efficiently. Remember that syntax errors are detected before your code runs, so fixing them is often straightforward once you know what to look for.
For production Python projects, especially those involving web scraping or API integrations, maintaining clean, syntactically correct code is essential. If you’re working on large-scale data collection projects, consider using managed solutions like Thordata’s web scraping tools to handle infrastructure concerns while you focus on your application logic. You can manage your scraping tasks and view results through the Thordata Dashboard.
You can find all the source code examples from this guide, along with their fixes, in our GitHub repository. If you’re interested in learning more about web scraping with Python, check out our comprehensive tutorials and examples in the Python SDK repository.
Frequently asked questions
What are Python syntax errors?
Python syntax errors occur when the Python parser cannot understand the structure of your code. They violate Python’s grammatical rules and must be fixed before the code can execute. Unlike runtime errors, syntax errors prevent your code from running at all.
How do I read Python syntax error messages?
Python error messages provide: 1) File path and line number where the error occurred, 2) The problematic code line, 3) An error indicator (^) pointing to the approximate location, and 4) An error type and message describing what went wrong. Start at the caret symbol and check the line before it if needed.
What are the most common Python syntax errors?
The most common Python syntax errors include: missing colons after function definitions and control statements, indentation errors, mismatched quotes, missing commas in lists/dictionaries, using = instead of == for comparison, using reserved keywords as variable names, and variable names starting with numbers.
How can I prevent Python syntax errors?
To prevent Python syntax errors: use a modern IDE with real-time syntax checking, configure your editor to use 4 spaces for indentation, use code formatters like Black or autopep8, follow PEP 8 style guidelines, write tests, and use linters like pylint or flake8.
What’s the difference between syntax errors and runtime errors?
Syntax errors are detected during parsing (before execution) and prevent code from running. Runtime errors occur during execution and cause the program to crash. Logical errors are syntactically valid but produce incorrect output.
About the author
Kael is a Senior Technical Copywriter at Thordata. He works closely with data engineers to document best practices for bypassing anti-bot protections. He specializes in explaining complex infrastructure concepts like residential proxies and TLS fingerprinting to developer audiences.
The thordata Blog offers all its content in its original form and solely for informational intent. We do not offer any guarantees regarding the information found on the thordata Blog or any external sites that it may direct you to. It is essential that you seek legal counsel and thoroughly examine the specific terms of service of any website before engaging in any scraping endeavors, or obtain a scraping permit if required.
Looking for
Top-Tier Residential Proxies?
您在寻找顶级高质量的住宅代理吗?
How to Make HTTP Requests in Node.js With Fetch API (2026)
How to Make HTTP Requests in Node.js With Fetch API (20 […]
Unknown
2026-03-03
How to Scrape Job Postings in 2026: Complete Guide
How to Scrape Job Postings in 2026: Complete Guide Cont […]
Unknown
2026-03-03
BeautifulSoup Tutorial 2026: Parse HTML Data With Python
BeautifulSoup Tutorial 2026: Parse HTML Data With Pytho […]
Unknown
2026-03-03
How to Scrape Glassdoor Data with Python?
In this tutorial, master how t ...
Anna Stankevičiūtė
2026-03-02
Best B2B Data Providers of 2026: Unlock Hyper-Targeted Leads & Actionable Insights
Yulia Taylor Last updated on 2026-02-08 5 min read In 2 […]
Unknown
2026-03-02
5 Best Etsy Scraper Tools in 2026
This article evaluates the top ...
Yulia Taylor
2026-02-09
What is a Headless Browser? Top 5 Popular Tools
A headless browser is a browse ...
Yulia Taylor
2026-02-07
Best Anti-Detection Browser in 2026
This article mainly introduces ...
Xyla Huxley
2026-02-06
What Is a UDP Proxy? Use Cases and Limits
This article primarily explain ...
Xyla Huxley
2026-02-06