{"id":20710030,"url":"https://github.com/oxylabs/python-syntax-errors","last_synced_at":"2026-04-06T04:32:25.877Z","repository":{"id":162927705,"uuid":"638140667","full_name":"oxylabs/python-syntax-errors","owner":"oxylabs","description":"A practical guide to reading Python syntax errors and fixing them.","archived":false,"fork":false,"pushed_at":"2025-06-26T08:29:25.000Z","size":126,"stargazers_count":2,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-06-26T09:34:58.401Z","etag":null,"topics":["amazon-scraper-python","github-python","how-to","python","python-ecommerce","python-image-scraper","python-web-crawler","scraper-python","scraping","serp-api-python","solve","syntax-errors","syntaxerror","web-scraping"],"latest_commit_sha":null,"homepage":"https://oxylabs.io/blog/python-syntax-errors","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/oxylabs.png","metadata":{"files":{"readme":"readme.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2023-05-09T07:04:13.000Z","updated_at":"2025-06-26T08:29:29.000Z","dependencies_parsed_at":null,"dependency_job_id":"6487b2ec-49ec-4abd-b213-245c59a7d57f","html_url":"https://github.com/oxylabs/python-syntax-errors","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/oxylabs/python-syntax-errors","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/oxylabs%2Fpython-syntax-errors","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/oxylabs%2Fpython-syntax-errors/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/oxylabs%2Fpython-syntax-errors/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/oxylabs%2Fpython-syntax-errors/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/oxylabs","download_url":"https://codeload.github.com/oxylabs/python-syntax-errors/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/oxylabs%2Fpython-syntax-errors/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":31460089,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-05T21:22:52.476Z","status":"online","status_checked_at":"2026-04-06T02:00:07.287Z","response_time":112,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["amazon-scraper-python","github-python","how-to","python","python-ecommerce","python-image-scraper","python-web-crawler","scraper-python","scraping","serp-api-python","solve","syntax-errors","syntaxerror","web-scraping"],"created_at":"2024-11-17T02:09:35.468Z","updated_at":"2026-04-06T04:32:25.870Z","avatar_url":"https://github.com/oxylabs.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Python Syntax Errors: Common Mistakes and How to Fix Them\n\n[![Oxylabs promo code](https://raw.githubusercontent.com/oxylabs/product-integrations/refs/heads/master/Affiliate-Universal-1090x275.png)]([https://oxylabs.go2cloud.org/aff_c?offer_id=7\u0026aff_id=877\u0026url_id=112](https://oxylabs.io/pages/gitoxy?utm_source=877\u0026utm_medium=affiliate\u0026groupid=877\u0026utm_content=python-syntax-errors-github\u0026transaction_id=102f49063ab94276ae8f116d224b67))\n\n[![](https://dcbadge.limes.pink/api/server/Pds3gBmKMH?style=for-the-badge\u0026theme=discord)](https://discord.gg/Pds3gBmKMH) [![YouTube](https://img.shields.io/badge/YouTube-Oxylabs-red?style=for-the-badge\u0026logo=youtube\u0026logoColor=white)](https://www.youtube.com/@oxylabs)\n\n  - [How to read Python syntax errors](#how-to-read-python-syntax-errors)\n  - [How to fix syntax errors](#how-to-fix-syntax-errors)\n    * [Misplaced, missing, or mismatched punctuation](#misplaced-missing-or-mismatched-punctuation)\n    * [Misspelled, misplaced, or missing Python keywords](#misspelled-misplaced-or-missing-python-keywords)\n    * [Illegal characters in variable names](#illegal-characters-in-variable-names)\n    * [Incorrect indentation](#incorrect-indentation)\n    * [Incorrect use of the assignment operator (=)](#incorrect-use-of-the-assignment-operator)\n\n\nThis article examines how to read and fix Python syntax errors with the\nhelp of practical web scraping examples.\n\nFor a detailed explanation, see our [\u003cu\u003eblog post\u003c/u\u003e](https://oxylabs.io/blog/python-syntax-errors).\n\n## How to read Python syntax errors\n\nWhen you get an error message, Python tries to point to the root cause\nof the error. Sometimes, the message tells exactly what’s the problem,\nbut other times it’s unclear and even confusing. This happens because\nPython locates the first place where it couldn’t understand the syntax;\ntherefore, it might show an error in a code line that goes after the\nactual error.\n\nKnowing how to read Python error messages goes a long way to save both\ntime and effort. So let’s examine a Python web scraping code sample that\nraises two syntax errors:\n\n```python\nprices = {\"price1\": 9.99, \"price2\": 13.48 \"price3\": 10.99, \"price4\": 15.01}\nprice_found = False\nfor key value in prices.items():\n    if 10 \u003c= value \u003c= 14.99:\n        print(key + \":\", value)\n        price_found = True\nif not price_found:\n    print(\"There are no prices between $10 and $14.99\")\n```\n\nIn this example, we have a dictionary of different `prices`. We use a\n`for` loop to find and print the prices between $10 and $14.99. The\n`price_found` variable uses a boolean value to determine whether such\na price was found in the dictionary.\n\nWhen executed, Python points to the first invalid syntax error it came\nupon, even though there are two more errors along the way. The first\nerror message looks like this:\n![](/images/syntax_error_1.png)\n\nInformation in the yellow box helps us determine the location of the\nerror, and the green box includes more details about the error itself.\nThe full message can be separated into four main elements:\n\n1.  **The path directory** and **name** of the file where the error occurred;\n\n2.  **The line number** and the **faulty code line** where the error was first encountered;\n\n3.  **The carets (^)** that pinpoint the place of the error;\n\n4.  **The error message** determines the error type, followed by additional information that may help fix the problem.\n\nThe code sample produced a syntax error found in the first line of code\n– the `prices` dictionary. The carets indicate that the error occurred\nbetween `“price2”: 13.48` and `“price3”: 10.99`, and the invalid\nsyntax message says that perhaps we forgot to add a comma between the\nitems in our dictionary. That’s exactly it! The Python interpreter\nsuggested the correct solution, so let’s update the code:\n\n```python\nprices = {\"price1\": 9.99, \"price2\": 13.48, \"price3\": 10.99, \"price4\": 15.01}\n```\n\nNow, rerun the code to see what’s the second syntax error:\n![](/images/syntax_error_2.png)\n\nThis time, the carets fail to pinpoint the exact location of the error,\nand the `SyntaxError` message doesn’t include additional information\nabout the possible solution. In such cases, the rule of thumb would be\nto examine the code that comes just before the carets. In the code\nsample, the syntax error is raised because there’s a missing comma\nbetween the variables `key` and `value` in the `for` loop. The\nsyntactically correct code ine should look like this:\n\n```python\nfor key, value in prices.items():\n```\n\n## How to fix syntax errors\n\n### Misplaced, missing, or mismatched punctuation\n\n1.  Ensure that parentheses `()`, brackets `[]`, and braces `{}` are properly closed. When left unclosed, the Python interpreter treats everything following the first parenthesis, bracket, or brace as a single statement. Take a look at this web scraping code sample that sends parsing instructions to our [web scraping tool](https://oxylabs.io/products/scraper-api/web):\n\n```python\npayload = {\n    \"source\": \"universal\",\n    \"url\": \"https://sandbox.oxylabs.io/products/1\",\n    \"parse\": True,\n    \"parsing_instructions\": {\n        \"title\": {\n            \"_fns\": [\n                {\n                    \"_fn\": \"css_one\",\n                    \"_args\": [\"h2\"]\n                }\n            ]\n        }\n    }\n\n# Error message\n  File \"\u003cstdin\u003e\", line 1\n    payload = {\n              ^\nSyntaxError: '{' was never closed\n```\n\nAt first glance, it may look like the `payload` was closed with braces, but the Python interpreter raises a syntax error that says otherwise. You can fix the error by closing the `payload`:\n\n\n```python\npayload = {\n    \"source\": \"universal\",\n    \"url\": \"https://sandbox.oxylabs.io/products/1\",\n    \"parse\": True,\n    \"parsing_instructions\": {\n        \"title\": {\n            \"_fns\": [\n                {\n                    \"_fn\": \"css_one\",\n                    \"_args\": [\"h2\"]\n                }\n            ]\n        }\n    }\n} # Add the missing brace\n```\n\n2.  Make sure you close a string with proper quotes. For example, if you started your string with a single quote ‘, then use a single quote again at the end of your string. The below code snippet illustrates this:\n\n```python\nlist_of_URLs = (\n    'https://example.com/1',\n    'https://example.com/2\",\n    'https://example.com/3\n)\nprint(list_of_URLs)\n\n# Error message\n  File \"\u003cstdin\u003e\", line 3\n    'https://example.com/2\",\n    ^\nSyntaxError: unterminated string literal (detected at line 3)\n```\n\nThis example has two errors, but as you can see, the interpreter shows\nonly the first syntax error. It pinpoints the issue precisely, which is\nthe use of a single quote at the start, and a double quote at the end to\nclose the string.\n\nThe second error is in the third example URL, which isn’t closed with a\nquotation mark at all. The syntactically correct version would look like\nthis:\n\n```python\nlist_of_URLs = (\n    'https://example.com/1',\n    'https://example.com/2',\n    'https://example.com/3'\n)\nprint(list_of_URLs)\n```\n\nWhen the string content itself contains quotation marks, use single\n`‘`, double `“`, and/or triple `‘’’` quotes to specify where the\nstring starts and ends. For instance:\n\n```python\nprint(\"In this example, there's a \"quote within 'a quote'\", which we separate with double and single quotes.\")\n\n# Error message\n  File \"\u003cstdin\u003e\", line 1\n    print(\"In this example, there's a \"quote within 'a quote'\", which we separate with double and single quotes.\")\n          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\nSyntaxError: invalid syntax. Perhaps you forgot a comma?\n```\n\nThe interpreter shows where the error occurred, and you can see that the\ncarets end within the second double quotation mark. To fix the syntax\nerror, you can wrap the whole string in triple quotes (either `’’’` or\n`“””`):\n\n```python\nprint(\"\"\"In this example, there's a \"quote within 'a quote'\", which we specify with double and single quotes.\"\"\")\n```\n\n3.  When passing multiple arguments or values, make sure to separate them with commas. Consider the following web scraping example that encapsulates HTTP headers in the `headers` dictionary:\n\n```python\nheaders = {\n    'Accept': 'text/html',\n    'Accept-Encoding': 'gzip, deflate, br',\n    'Accept-Language': 'en-US, en;q=0.9'\n    'Connection': 'keep-alive'\n}\n\n# Error message\n  File \"\u003cstdin\u003e\", line 5\n    'Connection': 'keep-alive'\n                ^\nSyntaxError: invalid syntax\n```\n\nAgain, the interpreter fails to show precisely where the issue is, but\nas a rule of thumb, you can expect the actual invalid syntax error to be\nbefore where the caret points. You can fix the error by adding the\nmissing comma after the `‘Accept-Language’` argument:\n\n```python\nheaders = {\n    'Accept': 'text/html',\n    'Accept-Encoding': 'gzip, deflate, br',\n    'Accept-Language': 'en-US, en;q=0.9',\n    'Connection': 'keep-alive'\n}\n```\n\n4.  Don’t forget to add a colon `:` at the end of a function or a compound statement, like `if`, `for`, `while`, `def`, etc. Let’s see an example of web scraping:\n\n```python\ndef extract_product_data()\n    for url in product_urls\n        response = requests.get(url, headers=headers)\n        soup = BeautifulSoup(response.content, 'html.parser')\n        title = soup.find(\"h1\").text\n        price = soup.find(\"span\", {\"itemprop\": \"price\"}).text\n        product_data.append({\n            \"title\": title,\n            \"price\": price,\n        })\n\n# Error message\nFile \"\u003cstdin\u003e\", line 1\n    def extract_product_data()\n                              ^\nSyntaxError: expected ':'\n```\n\nThis time, the interpreter shows the exact place where the error\noccurred and hints as to what could be done to fix the issue. In the\nabove example, the `def` function and the `for` loop are missing a\ncolon, so we can update our code:\n\n```python\ndef extract_product_data():\n    for url in product_urls:\n```\n\n### Misspelled, misplaced, or missing Python keywords\n\n1.  Make sure you’re not using the reserved Python keywords to name variables and functions. If you’re unsure whether a word is or isn’t a Python keyword, check it with the [\u003cu\u003ekeyword module\u003c/u\u003e](https://docs.python.org/3/library/keyword.html) in Python or look it up in the [\u003cu\u003ereserved keywords list\u003c/u\u003e](https://docs.python.org/3.11/reference/lexical_analysis.html#keywords). Many IDEs, like PyCharm and VS Code, highlight the reserved keywords, which is extremely helpful. The code snippet below uses the reserved keyword \\`pass\\` to hold the password value, which causes the syntax error message:\n\n```python\nuser = 'username1'\npass = 'password1'\n\n# Error message\n  File \"\u003cstdin\u003e\", line 2\n    pass = 'password1'\n         ^\nSyntaxError: invalid syntax\n```\n\n2.  Ensure that you haven’t misspelled a Python keyword. For instance:\n\n```python\nimport time\nfrom requests impotr Session\n\n# Error message\n  File \"\u003cstdin\u003e\", line 2\n    from requests impotr Session\n                  ^^^^^^\nSyntaxError: invalid syntax\n```\n\nThis code sample tries to import the `Session` object from the\nrequests library. However, the Python keyword `import` is misspelled\nas `impotr`, which raises an invalid syntax error.\n\n3.  Placing a Python keyword where it shouldn't be will also raise an error. Make sure that the Python keyword is used in the correct syntactical order and follows the rules specific to that keyword. Consider the following example:\n\n```python\nimport time\nimport Session from requests\n\n# Error message\n  File \"\u003cstdin\u003e\", line 2\n    import Session from requests\n                   ^^^^\nSyntaxError: invalid syntax\n```\n\nHere, we see an invalid syntax error because the Python keyword `from`\ndoesn’t follow the correct syntactical order. The fixed code should look\nlike this:\n\n```python\nimport time\nfrom requests import Session\n```\n\n### Illegal characters in variable names\n\nPython variables have to follow certain naming conventions:\n\n1.  You can’t use blank spaces in variable names. The best solution is to use the underscore character. For example, if you want a variable named “two words”, it should be written as `two_words`, `twowords`, `TwoWords`, `twoWords`, or `Twowords`.\n\n2.  Variables are case-sensitive, meaning `example1` and `Example1` are two different variables. Take this into account when creating variables and calling them later in your code.\n\n3.  Don’t start a variable with a number. Python will give you a syntax error:\n\n```python\nresponse1 = requests.get(url)\n2response = requests.post(url)\n\n# Error message\n  File \"\u003cstdin\u003e\", line 2\n    2response = requests.post(url)\n    ^\nSyntaxError: invalid decimal literal\n```\n\nAs you can see, the interpreter allows using numbers in variable names\nbut not when the variable names start with a number.\n\n4.  Variable names can only use letters, numbers, and underscores. Any other characters used in the name will produce a syntax error.\n\n### Incorrect indentation\n\n1.  Remember that certain Python commands, like compound statements and functions, require indentation to define the scope of the command. So, ensure that such commands in your code are indented properly. For instance:\n\n```python\nprices = (16.99, 13.68, 24.98, 14.99)\n\n\ndef print_price():\n    for price in prices:\n    if price \u003c 15:\n        print(price)\n\nprint_price()\n\n\n# Error message 1\n  File \"\u003cstdin\u003e\",line 6\n    if price \u003c 15:\n    ^\nIndentationError: expected an indented block after 'for' statement on line 5\n\n\n# Error message 2\n  File \"\u003cstdin\u003e\", line 7\n    print(price)\n    ^\nIndentationError: expected an indented block after 'if' statement on line 6\n```\n\nThe first error message indicates that the `if` statement requires an\nindented block. After fixing that and running the code, we encounter the\nsecond error message that tells us the `print` statement is outside\nthe `if` statement and requires another indent. Fix the code with the\ncorrect indentation:\n\n```python\nprices = (16.99, 13.68, 24.98, 14.99)\n\n\ndef print_price():\n    for price in prices:\n        if price \u003c 15:\n            print(price)\n\nprint_price()\n```\n\n2.  Use consistent indentation marks: either all spaces or all tabs. Don’t mix them up, as it can reduce the readability of your code, in turn making it difficult to find the incorrect indentation just by looking at the code. Most Python IDEs highlight indentation errors before running the code, so you can reformat the file automatically to fix the indentation. Let’s take the above code sample and fix the first error message by adding a single space in front of the `if` statement:\n\n```python\nprices = (16.99, 13.68, 24.98, 14.99)\n\n\ndef print_price():\n    for price in prices:\n     if price \u003c 15:\n        print(price)\n\nprint_price()\n```\n\nThe code works without errors and prints the correct result. However,\nyou can see how the mix of spaces and tabs makes the code a little\nharder to read. Using this method can bring about unnecessary syntax\nerrors when they can be avoided by sticking to either spaces or tabs\nthroughout the code.\n\n### Incorrect use of the assignment operator\n\n1.  Ensure you aren’t assigning values to functions or literals with the assignment operator `=`. You can only assign values to variables. Here’s an overview of some examples:\n\n```python\nprice = 10.98\ntype(price) = float\n\n# Error message\n  File \"\u003cstdin\u003e\", line 2\n    type(price) = float\n    ^^^^^^^^^^^\nSyntaxError: cannot assign to function call here. Maybe you meant '==' instead of '='?\n\n\n\"price\" = 10.98\n\n# Error message\n  File \"\u003cstdin\u003e\", line 1\n    \"price\" = 10.98\n    ^^^^^^^\nSyntaxError: cannot assign to literal here. Maybe you meant '==' instead of '='?\n```\n\nIn the first code sample, we want to check whether the value `10.98`\nis a float type. The Python interpreter raises an error since the\nassignment operator can’t be used to assign a value to a function. The\ncorrect way to accomplish this is with one the following code samples:\n\n```python\nprice = 10.98\nprint(type(price))\n\n# or\n\nprice = 10.98\nis_float = type(price) == float\nprint(is_float)\n```\n\n2.  Assign values in a dictionary with a colon `:` and not an assignment operator `=`. Let’s take a previous code sample and modify it to incorrectly use the assignment operator instead of colons:\n\n```python\nheaders = {\n    'Accept' = 'text/html',\n    'Accept-Encoding' = 'gzip, deflate, br',\n    'Accept-Language' = 'en-US, en;q=0.9',\n    'Connection' = 'keep-alive'\n}\n\n\n# Error message\n  File \"\u003cstdin\u003e\", line 2\n    'Accept' = 'text/html',\n    ^^^^^^^^\nSyntaxError: cannot assign to literal here. Maybe you meant '==' instead of '='?\n```\n\n3.  Use `==` when comparing objects based on their values. For instance:\n\n```python\nprice_1 = 200.99\nprice_2 = 200.98\n\ncompare = (price_1 = price_2)\nprint(compare)\n\n# Error message\n  File \"\u003cstdin\u003e\", line 4\n    compare = (price_1 = price_2)\n               ^^^^^^^^^^^^^^^^^\nSyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?\n```\n\nYou can fix the issue by using the double equal sign `==` between `price_1` and `price_2` instead of `=`, which will print the\ncorrect result.\n\nCheck out our [\u003cu\u003eblog post\u003c/u\u003e](https://oxylabs.io/blog/python-syntax-errors) to find out more about Python syntax errors. There, you’ll find an explanation of syntax errors, their common causes, and some tips for avoiding them.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Foxylabs%2Fpython-syntax-errors","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Foxylabs%2Fpython-syntax-errors","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Foxylabs%2Fpython-syntax-errors/lists"}