Unterminated string literal python ошибка

Cover image for How to fix "SyntaxError: unterminated string literal" in Python

Update: This post was originally published on my blog decodingweb.dev, where you can read the latest version for a 💯 user experience. ~reza

Python raises “SyntaxError: unterminated string literal” when a string value doesn’t have a closing quotation mark.

This syntax error usually occurs owing to a missing quotation mark or an invalid multi-line string. Here’s what the error looks like on Python version 3.11:

File /dwd/sandbox/test.py, line 1
    book_title = 'Head First Python
                 ^
SyntaxError: unterminated string literal (detected at line 1)

Enter fullscreen mode

Exit fullscreen mode

On the other hand, the error «SyntaxError: unterminated string literal» means Python was expecting a closing quotation mark, but it didn’t encounter any:

# 🚫 SyntaxError: unterminated string literal (detected at line 1)
book_title = 'Head First Python

Enter fullscreen mode

Exit fullscreen mode

Adding the missing quotation mark fixes the problem instantly:

# ✅ Correct
book_title = 'Head First Python'

Enter fullscreen mode

Exit fullscreen mode

How to fix «SyntaxError: unterminated string literal»

The error «SyntaxError: unterminated string literal» occurs under various scenarios:

  1. Missing the closing quotation mark
  2. When a string value ends with a backslash ()
  3. Opening and closing quotation marks mismatch
  4. A multi-line string enclosed with " or '
  5. A missing backslash!
  6. Multi-line strings enclosed with quadruple quotes!

Missing the closing quotation mark: The most common reason behind this error is to forget to close your string with a quotation mark — whether it’s a single, double, or triple quotation mark.

# 🚫 SyntaxError: unterminated string literal (detected at line 1)
book_title = 'Head First Python

Enter fullscreen mode

Exit fullscreen mode

Needless to say, adding the missing end fixes the problem:

# ✅ Correct
book_title = 'Head First Python'

Enter fullscreen mode

Exit fullscreen mode

When a string value ends with a backslash (): Based on Python semantics, a pair of quotation marks work as a boundary for a string literal.

Putting a backslash before a quotation mark will neutralize it and make it an ordinary character. In the programming terminology, it’s called an escape character.

This is helpful when you want to include a quotation mark in your string, but you don’t want it to interefer with its surrounding quotation marks:

message = 'I' m good'

Enter fullscreen mode

Exit fullscreen mode

That said, if you use the backslash before the ending quotation mark, it won’t be a boundary character anymore.

Imagine you need to define a string that ends with a like a file path on Windows

# 🚫 SyntaxError: unterminated string literal (detected at line 1)
file_dir = 'C:files'

Enter fullscreen mode

Exit fullscreen mode

In the above code, the last escapes the quotation mark, leaving our string unterminated. As a result, Python raises «SyntaxError: unterminated string literal».

To fix it, we use a double backslash \ instead of one. It’s like using its effect against itself; the first escapes the its following backslash. As a result, we’ll have our backslash in the string (as an ordinary character), and the quoting effect of ' remains intact.

# ✅ Escaping a slash in a string literal
file_dir = 'C:files'

Enter fullscreen mode

Exit fullscreen mode

Opening and closing quotation marks mismatch: The opening and closing quotation marks must be identical, meaning if the opening quotation mark is ", the closing part must be " too.

The following code raises the error:

# 🚫 SyntaxError: unterminated string literal (detected at line 1)
book_title = "Python Head First'

Enter fullscreen mode

Exit fullscreen mode

No matter which one you choose, they need to be identical:

# ✅ Opening and closing quotation marks match
book_title = 'Python Head First'

Enter fullscreen mode

Exit fullscreen mode

A multi-line string enclosed with " or ': If you use ' or " to quote a string literal, Python will look for the closing quotation mark on the same line.

Python is an interpreted language that executes lines one after another. So every statement is assumed to be on one line. A new line marks the end of a Python statement and the beginning of another.

So if you define a string literal in multiple lines, you’ll get the syntax error:

# 🚫 SyntaxError: unterminated string literal (detected at line 1)
message = 'Python is a high-level, 
general-purpose 
programming language'

Enter fullscreen mode

Exit fullscreen mode

In the above code, the first line doesn’t end with a quotation mark.

If you want a string literal to span across several lines, you should use the triple quotes (""" or ''') instead:

# ✅ The correct way of defining multi-line strings
message = '''Python is a high-level, 
general-purpose 
programming language'''

Enter fullscreen mode

Exit fullscreen mode

Multi-line strings enclosed with quadruple quotes: As mentioned earlier, to create multi-line strings, we use triple quotes. But what happens if you use quadruple quotes?

The opening part would be ok, as the fourth quote would be considered a part of the string. However, the closing part will cause a SyntaxError.

Since Python expects the closing part to be triple quotes, the fourth quotation mark would be considered a separate opening without a closing part, and it raises the «SyntaxError: unterminated string literal» error.

# 🚫 SyntaxError: unterminated string literal (detected at line 3)
message = ''''Python is a high-level, 
general-purpose 
programming language''''

Enter fullscreen mode

Exit fullscreen mode

Always make sure you’re not using quadruple quotes by mistake.

A missing slash: Another way to span Python statements across multiple lines is by marking each line with a backslash. This backslash () escapes the hidden newline character (n) and makes Python continue parsing statements until it reaches a newline character.

You can use this technique as an alternative to the triple quotes:

# ✅ The correct way of defining multi-line strings with ''
message = 'Python is a high-level, 
general-purpose 
programming language'

Enter fullscreen mode

Exit fullscreen mode

Now, if you forget the in the second line, Python will expect to see the closing quotation mark on that line:

# 🚫 SyntaxError: unterminated string literal (detected at line 2)
message = 'Python is a high-level, 
general-purpose 
programming language'

Enter fullscreen mode

Exit fullscreen mode

If you’re taking this approach, all lines should end with , except for the last line, which ends with the closing quotation mark.

✋ Please note: Since the is supposed to escape the newline character (the hidden last character), no space should follow the . If you leave a space after the backslash, the newline character wouldn’t be affected, and Python will expect the statement to end on the current line.

Alright, I think it does it. I hope this quick guide helped you solve your problem.

Thanks for reading.


❤️ You might like:

  • SyntaxError: EOL while scanning string literal in Python
  • SyntaxError: cannot assign to expression here in Python
  • SyntaxError: cannot assign to literal here in Python
  • TypeError: ‘str’ object is not callable in Python (Fixed)

Решил запустить скрипт сделал все по инструкции и тут выскакивает такое. Не подскажите как это исправить друзья программисты буду очень благодарен(
Ошибка

C:UsersНатальяAppDataLocalProgramsPythonPython311python.exe C:UsersНатальяPycharmProjectspythonProject1main.py 
  File "C:UsersНатальяPycharmProjectspythonProject1main.py", line 35
    unq_filter_params =["colorbalance=rs=.3","colorbalance=gs=-
                                             ^
SyntaxError: unterminated string literal (detected at line 35)

Process finished with exit code 1

Сам код

import moviepy
from moviepy.editor import *
import random
from pathlib import Path
import string

def create_file_list(folder):
    return [str(f) for f in Path(folder).iterdir()]

def create_image_list(folder):
    image_list=[]
    folder = Path(folder)
    if folder.is_file():
        image = ImageClip(str(folder),duration=1)
        image_list.append(image)
    if folder.is_dir():
        for file in sorted(folder.iterdir(), reverse=True):
            image = ImageClip(str(file),duration=1)
            image_list.append(image)
    return image_list

def filename(folder):
    file_name = ''.join(random.choice(string.ascii_lowercase)
for i in range(5))
    file_name = str(Path(folder).joinpath(file_name + '.mp4'))
    return file_name

#Папка для сохранения видео
result_folder = r'C:UsersНатальяDesktopSAVE'
#Папка с картиками
images = create_image_list(r'C:UsersНатальяDesktopPNG')
#Папка с видео которые будут обработаны
video_ls = create_file_list(r'C:UsersНатальяDesktopVIDEO')
#Фильтрыpip
unq_filter_params =["colorbalance=rs=.3","colorbalance=gs=-
0.20","colorbalance=gs=0.20","colorbalance=bs=-
0.30","colorbalance=bs=0.30","colorbalance=rm=0.30","colorbalanc
e=rm=-0.30","colorbalance=gm=-0.25","colorbalance=bm=-
0.25","colorbalance=rh=-0.15","colorbalance=gh=-
0.20","colorbalance=bh=-0.20"]

Скриншот фрагмента кода удален модератором.

How to fix SyntaxError: unterminated string literal (detected at line 8) in python, in this scenario, I forgot by mistakenly closing quotes ( ” ) with f string different code lines, especially 1st line and last line code that is why we face this error in python. This is one of the command errors in python, If face this type of error just find where you miss the opening and closing parentheses ( “)”  just enter then our code error free see the below code.

Wrong Code: unterminated string literal python

# Just create age input variable
a = input("What is Your Current age?n")

Y = 101 - int(a)
M = Y * 12
W = M * 4
D = W * 7
print(f"You have {D} Days {W} Weeks, {M} Months And {Y} Years Left In Your Life)
print("Hello World")

Error Massage

  File "/home/kali/python/webproject/error/main.py", line 8
    print(f"You have {D} Days {W} Weeks, {M} Months And {Y} Years Left In Your Life)
          ^
SyntaxError: unterminated string literal (detected at line 8)

Wrong code line

Missing closing quotes ( ” ).

print(f"You have {D} Days {W} Weeks, {M} Months And {Y} Years Left In Your Life)

Correct code line

print(f"You have {D} Days {W} Weeks, {M} Months And {Y} Years Left In Your Life")

print(” “).

Entire Correct Code line

# Just create age input variable
a = input("What is Your Current age?n")

Y = 101 - int(a)
M = Y * 12
W = M * 4
D = W * 7
print(f"You have {D} Days {W} Weeks, {M} Months And {Y} Years Left In Your Life")
print("Hello World")

What is unterminated string literal Python?

Syntax in python sets forth a specific symbol for coding elements like opening and closing quotes (“  “ ), Whenever we miss the closing quotes with f string that time we face SyntaxError: unterminated string literal In Python. See the above example.

How to Fix unterminated string literal Python?

Syntax in python sets forth a specific symbol for coding elements like opening and closing quotes (), Whenever we miss the closing quotes with f string that time we face SyntaxError: unterminated string literal so we need to find in which line of code we miss special closing quotes ( “ )symbol and need to enter correct symbols, See the above example.

For more information visit Amol Blog Code YouTube Channel.

I am trying to use a shutil script I found but it receives SyntaxError: unterminated string literal (detected at line 4). Any assistance would be appreciated to fixing this or new script

import shutil
import os

source = r"C:Users[username]Downloads"
dest1 = r" C:Users[username]DesktopReports14"
dest2 = r" C:Users[username]DesktopReports52"
dest3 = r" C:Users[username]DesktopReports59"

files = os.listdir(source)

for f in files:
   
 if (f.startswith("Log 14")):
        shutil.move(f, dest1)
    elif (f.startswith("Log 54")):
        shutil.move(f, dest2)

asked Dec 9, 2021 at 20:42

Ric 's user avatar

Ric Ric

211 gold badge1 silver badge3 bronze badges

8

Watch out for smart quotes . They need to be double quotes ".

You had smart quotes instead of normal ones. Indenting is also not correct.

Here is the fixed code:

import shutil
import os

source = "C:\Users\[username]\Downloads\"
dest1 = "C:\Users\[username]\Desktop\Reports\14"
dest2 = "C:\Users\[username]\Desktop\Reports\52"
dest3 = "C:\Users\[username]\Desktop\Reports\59"

files = os.listdir(source)

for f in files:
    if f.startswith("Log 14"):
        shutil.move(source + f, dest1)
    elif f.startswith("Log 54"):
        shutil.move(source + f, dest2)

wjandrea's user avatar

wjandrea

27.3k9 gold badges59 silver badges80 bronze badges

answered Dec 9, 2021 at 21:48

norbot's user avatar

norbotnorbot

1876 bronze badges

2

Smart Quotation Marks strike again.

Using BabelStone, one can determine the unicode identification of each character in your code.

The start/ending quotes you’re used to are U0022. However, the end of the URL on dest2 ends with a different character, which is U201D. This is a different character. Easiest way to fix this is to retype out the quotation marks in your IDE.

Input: "”

U+0022 : QUOTATION MARK {double quote}
U+201D : RIGHT DOUBLE QUOTATION MARK {double comma quotation mark}

answered Dec 9, 2021 at 21:43

blackbrandt's user avatar

blackbrandtblackbrandt

1,9901 gold badge15 silver badges32 bronze badges

import os

if os.name == 'nt':    #check if windows 
  a='\'
else:
  a='/'


source = "C:"+a+"Users"+a+"[username]"+a+"Downloads"+a

answered Jul 7, 2022 at 8:21

RITESH 's user avatar

RITESH RITESH

851 silver badge4 bronze badges

3

Python Syntax Errors: Common Mistakes and How to Fix Them

  • How to read Python syntax errors
  • How to fix syntax errors
    • Misplaced, missing, or mismatched punctuation
    • Misspelled, misplaced, or missing Python keywords
    • Illegal characters in variable names
    • Incorrect indentation
    • Incorrect use of the assignment operator (=)

This article examines how to read and fix Python syntax errors with the
help of practical web scraping examples.

For a detailed explanation, see our blog post.

How to read Python syntax errors

When you get an error message, Python tries to point to the root cause
of the error. Sometimes, the message tells exactly what’s the problem,
but other times it’s unclear and even confusing. This happens because
Python locates the first place where it couldn’t understand the syntax;
therefore, it might show an error in a code line that goes after the
actual error.

Knowing how to read Python error messages goes a long way to save both
time and effort. So let’s examine a Python web scraping code sample that
raises two syntax errors:

prices = {"price1": 9.99, "price2": 13.48 "price3": 10.99, "price4": 15.01}
price_found = False
for key value in prices.items():
    if 10 <= value <= 14.99:
        print(key + ":", value)
        price_found = True
if not price_found:
    print("There are no prices between $10 and $14.99")

In this example, we have a dictionary of different prices. We use a
for loop to find and print the prices between $10 and $14.99. The
price_found variable uses a boolean value to determine whether such
a price was found in the dictionary.

When executed, Python points to the first invalid syntax error it came
upon, even though there are two more errors along the way. The first
error message looks like this:

Information in the yellow box helps us determine the location of the
error, and the green box includes more details about the error itself.
The full message can be separated into four main elements:

  1. The path directory and name of the file where the error occurred;

  2. The line number and the faulty code line where the error was first encountered;

  3. The carets (^) that pinpoint the place of the error;

  4. The error message determines the error type, followed by additional information that may help fix the problem.

The code sample produced a syntax error found in the first line of code
– the prices dictionary. The carets indicate that the error occurred
between “price2”: 13.48 and “price3”: 10.99, and the invalid
syntax message says that perhaps we forgot to add a comma between the
items in our dictionary. That’s exactly it! The Python interpreter
suggested the correct solution, so let’s update the code:

prices = {"price1": 9.99, "price2": 13.48, "price3": 10.99, "price4": 15.01}

Now, rerun the code to see what’s the second syntax error:

This time, the carets fail to pinpoint the exact location of the error,
and the SyntaxError message doesn’t include additional information
about the possible solution. In such cases, the rule of thumb would be
to examine the code that comes just before the carets. In the code
sample, the syntax error is raised because there’s a missing comma
between the variables key and value in the for loop. The
syntactically correct code ine should look like this:

for key, value in prices.items():

How to fix syntax errors

Misplaced, missing, or mismatched punctuation

  1. 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 a set of crawling instructions to our Web Crawler tool:
payload = {
    "url": "https://www.example.com/",
    "filters": {
        "crawl": [".*"],
        "process": [".*"],
        "max_depth": 1,
    "scrape_params": {
        "user_agent_type": "desktop",
    },
    "output": {
        "type_": "sitemap"
    }
}

# Error message
  File "<stdin>", line 1
    payload = {
              ^
SyntaxError: '{' was never closed

At first glance, it looks like the payload was closed with braces, but
the Python interpreter raises a syntax error that says otherwise. In
this particular case, the “filters” parameter isn’t closed with
braces, which the interpreter, unfortunately, doesn’t show in its
traceback. You can fix the error by closing the “filters” parameter:

payload = {
    "url": "https://www.amazon.com/",
    "filters": {
        "crawl": [".*"],
        "process": [".*"],
        "max_depth": 1
    }, # Add the missing brace
    "scrape_params": {
        "user_agent_type": "desktop",
    },
    "output": {
        "type_": "sitemap"
    }
}
  1. 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:
list_of_URLs = (
    'https://example.com/1',
    'https://example.com/2",
    'https://example.com/3
)
print(list_of_URLs)

# Error message
  File "<stdin>", line 3
    'https://example.com/2",
    ^
SyntaxError: unterminated string literal (detected at line 3)

This example has two errors, but as you can see, the interpreter shows
only the first syntax error. It pinpoints the issue precisely, which is
the use of a single quote at the start, and a double quote at the end to
close the string.

The second error is in the third example URL, which isn’t closed with a
quotation mark at all. The syntactically correct version would look like
this:

list_of_URLs = (
    'https://example.com/1',
    'https://example.com/2',
    'https://example.com/3'
)
print(list_of_URLs)

When the string content itself contains quotation marks, use single
, double , and/or triple ‘’’ quotes to specify where the
string starts and ends. For instance:

print("In this example, there's a "quote within 'a quote'", which we separate with double and single quotes.")

# Error message
  File "<stdin>", line 1
    print("In this example, there's a "quote within 'a quote'", which we separate with double and single quotes.")
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
SyntaxError: invalid syntax. Perhaps you forgot a comma?

The interpreter shows where the error occurred, and you can see that the
carets end within the second double quotation mark. To fix the syntax
error, you can wrap the whole string in triple quotes (either ’’’ or
“””):

print("""In this example, there's a "quote within 'a quote'", which we specify with double and single quotes.""")
  1. 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:
headers = {
    'Accept': 'text/html',
    'Accept-Encoding': 'gzip, deflate, br',
    'Accept-Language': 'en-US, en;q=0.9'
    'Connection': 'keep-alive'
}

# Error message
  File "<stdin>", line 5
    'Connection': 'keep-alive'
                ^
SyntaxError: invalid syntax

Again, the interpreter fails to show precisely where the issue is, but
as a rule of thumb, you can expect the actual invalid syntax error to be
before where the caret points. You can fix the error by adding the
missing comma after the ‘Accept-Language’ argument:

headers = {
    'Accept': 'text/html',
    'Accept-Encoding': 'gzip, deflate, br',
    'Accept-Language': 'en-US, en;q=0.9',
    'Connection': 'keep-alive'
}
  1. 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:
def extract_product_data()
    for url in product_urls
        response = requests.get(url, headers=headers)
        soup = BeautifulSoup(response.content, 'html.parser')
        title = soup.find("h1").text
        price = soup.find("span", {"itemprop": "price"}).text
        product_data.append({
            "title": title,
            "price": price,
        })

# Error message
File "<stdin>", line 1
    def extract_product_data()
                              ^
SyntaxError: expected ':'

This time, the interpreter shows the exact place where the error
occurred and hints as to what could be done to fix the issue. In the
above example, the def function and the for loop are missing a
colon, so we can update our code:

def extract_product_data():
    for url in product_urls:

Misspelled, misplaced, or missing Python keywords

  1. 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 keyword module in Python or look it up in the reserved keywords list. 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:
user = 'username1'
pass = 'password1'

# Error message
  File "<stdin>", line 2
    pass = 'password1'
         ^
SyntaxError: invalid syntax
  1. Ensure that you haven’t misspelled a Python keyword. For instance:
import time
from requests impotr Session

# Error message
  File "<stdin>", line 2
    from requests impotr Session
                  ^^^^^^
SyntaxError: invalid syntax

This code sample tries to import the Session object from the
requests library. However, the Python keyword import is misspelled
as impotr, which raises an invalid syntax error.

  1. 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:
import time
import Session from requests

# Error message
  File "<stdin>", line 2
    import Session from requests
                   ^^^^
SyntaxError: invalid syntax

Here, we see an invalid syntax error because the Python keyword from
doesn’t follow the correct syntactical order. The fixed code should look
like this:

import time
from requests import Session

Illegal characters in variable names

Python variables have to follow certain naming conventions:

  1. 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.

  2. 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.

  3. Don’t start a variable with a number. Python will give you a syntax error:

response1 = requests.get(url)
2response = requests.post(url)

# Error message
  File "<stdin>", line 2
    2response = requests.post(url)
    ^
SyntaxError: invalid decimal literal

As you can see, the interpreter allows using numbers in variable names
but not when the variable names start with a number.

  1. Variable names can only use letters, numbers, and underscores. Any other characters used in the name will produce a syntax error.

Incorrect indentation

  1. 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:
prices = (16.99, 13.68, 24.98, 14.99)


def print_price():
    for price in prices:
    if price < 15:
        print(price)

print_price()


# Error message 1
  File "<stdin>",line 6
    if price < 15:
    ^
IndentationError: expected an indented block after 'for' statement on line 5


# Error message 2
  File "<stdin>", line 7
    print(price)
    ^
IndentationError: expected an indented block after 'if' statement on line 6

The first error message indicates that the if statement requires an
indented block. After fixing that and running the code, we encounter the
second error message that tells us the print statement is outside
the if statement and requires another indent. Fix the code with the
correct indentation:

prices = (16.99, 13.68, 24.98, 14.99)


def print_price():
    for price in prices:
        if price < 15:
            print(price)

print_price()
  1. 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:
prices = (16.99, 13.68, 24.98, 14.99)


def print_price():
    for price in prices:
     if price < 15:
        print(price)

print_price()

The code works without errors and prints the correct result. However,
you can see how the mix of spaces and tabs makes the code a little
harder to read. Using this method can bring about unnecessary syntax
errors when they can be avoided by sticking to either spaces or tabs
throughout the code.

Incorrect use of the assignment operator

  1. 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:
price = 10.98
type(price) = float

# Error message
  File "<stdin>", line 2
    type(price) = float
    ^^^^^^^^^^^
SyntaxError: cannot assign to function call here. Maybe you meant '==' instead of '='?


"price" = 10.98

# Error message
  File "<stdin>", line 1
    "price" = 10.98
    ^^^^^^^
SyntaxError: cannot assign to literal here. Maybe you meant '==' instead of '='?

In the first code sample, we want to check whether the value 10.98
is a float type. The Python interpreter raises an error since the
assignment operator can’t be used to assign a value to a function. The
correct way to accomplish this is with one the following code samples:

price = 10.98
print(type(price))

# or

price = 10.98
is_float = type(price) == float
print(is_float)
  1. 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:
headers = {
    'Accept' = 'text/html',
    'Accept-Encoding' = 'gzip, deflate, br',
    'Accept-Language' = 'en-US, en;q=0.9',
    'Connection' = 'keep-alive'
}


# Error message
  File "<stdin>", line 2
    'Accept' = 'text/html',
    ^^^^^^^^
SyntaxError: cannot assign to literal here. Maybe you meant '==' instead of '='?
  1. Use == when comparing objects based on their values. For instance:
price_1 = 200.99
price_2 = 200.98

compare = (price_1 = price_2)
print(compare)

# Error message
  File "<stdin>", line 4
    compare = (price_1 = price_2)
               ^^^^^^^^^^^^^^^^^
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?

You can fix the issue by using the double equal sign == between price_1 and price_2 instead of =, which will print the
correct result.

Check out our blog post 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.

  • Unsupported operand type s for int and str python ошибка
  • Unsupported operand type s for float and float ошибка
  • Unsupported command 7 zip ошибка
  • Unrouteable address ошибка почты
  • Unresolved reference python ошибка