Syntaxerror invalid syntax python ошибка

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Identify Invalid Python Syntax

Python is known for its simple syntax. However, when you’re learning Python for the first time or when you’ve come to Python with a solid background in another programming language, you may run into some things that Python doesn’t allow. If you’ve ever received a SyntaxError when trying to run your Python code, then this guide can help you. Throughout this tutorial, you’ll see common examples of invalid syntax in Python and learn how to resolve the issue.

By the end of this tutorial, you’ll be able to:

  • Identify invalid syntax in Python
  • Make sense of SyntaxError tracebacks
  • Resolve invalid syntax or prevent it altogether

Invalid Syntax in Python

When you run your Python code, the interpreter will first parse it to convert it into Python byte code, which it will then execute. The interpreter will find any invalid syntax in Python during this first stage of program execution, also known as the parsing stage. If the interpreter can’t parse your Python code successfully, then this means that you used invalid syntax somewhere in your code. The interpreter will attempt to show you where that error occurred.

When you’re learning Python for the first time, it can be frustrating to get a SyntaxError. Python will attempt to help you determine where the invalid syntax is in your code, but the traceback it provides can be a little confusing. Sometimes, the code it points to is perfectly fine.

You can’t handle invalid syntax in Python like other exceptions. Even if you tried to wrap a try and except block around code with invalid syntax, you’d still see the interpreter raise a SyntaxError.

SyntaxError Exception and Traceback

When the interpreter encounters invalid syntax in Python code, it will raise a SyntaxError exception and provide a traceback with some helpful information to help you debug the error. Here’s some code that contains invalid syntax in Python:

 1# theofficefacts.py
 2ages = {
 3    'pam': 24,
 4    'jim': 24
 5    'michael': 43
 6}
 7print(f'Michael is {ages["michael"]} years old.')

You can see the invalid syntax in the dictionary literal on line 4. The second entry, 'jim', is missing a comma. If you tried to run this code as-is, then you’d get the following traceback:

$ python theofficefacts.py
File "theofficefacts.py", line 5
    'michael': 43
            ^
SyntaxError: invalid syntax

Note that the traceback message locates the error in line 5, not line 4. The Python interpreter is attempting to point out where the invalid syntax is. However, it can only really point to where it first noticed a problem. When you get a SyntaxError traceback and the code that the traceback is pointing to looks fine, then you’ll want to start moving backward through the code until you can determine what’s wrong.

In the example above, there isn’t a problem with leaving out a comma, depending on what comes after it. For example, there’s no problem with a missing comma after 'michael' in line 5. But once the interpreter encounters something that doesn’t make sense, it can only point you to the first thing it found that it couldn’t understand.

There are a few elements of a SyntaxError traceback that can help you determine where the invalid syntax is in your code:

  • The file name where the invalid syntax was encountered
  • The line number and reproduced line of code where the issue was encountered
  • A caret (^) on the line below the reproduced code, which shows you the point in the code that has a problem
  • The error message that comes after the exception type SyntaxError, which can provide information to help you determine the problem

In the example above, the file name given was theofficefacts.py, the line number was 5, and the caret pointed to the closing quote of the dictionary key michael. The SyntaxError traceback might not point to the real problem, but it will point to the first place where the interpreter couldn’t make sense of the syntax.

There are two other exceptions that you might see Python raise. These are equivalent to SyntaxError but have different names:

  1. IndentationError
  2. TabError

These exceptions both inherit from the SyntaxError class, but they’re special cases where indentation is concerned. An IndentationError is raised when the indentation levels of your code don’t match up. A TabError is raised when your code uses both tabs and spaces in the same file. You’ll take a closer look at these exceptions in a later section.

Common Syntax Problems

When you encounter a SyntaxError for the first time, it’s helpful to know why there was a problem and what you might do to fix the invalid syntax in your Python code. In the sections below, you’ll see some of the more common reasons that a SyntaxError might be raised and how you can fix them.

Misusing the Assignment Operator (=)

There are several cases in Python where you’re not able to make assignments to objects. Some examples are assigning to literals and function calls. In the code block below, you can see a few examples that attempt to do this and the resulting SyntaxError tracebacks:

>>>

>>> len('hello') = 5
  File "<stdin>", line 1
SyntaxError: can't assign to function call

>>> 'foo' = 1
  File "<stdin>", line 1
SyntaxError: can't assign to literal

>>> 1 = 'foo'
  File "<stdin>", line 1
SyntaxError: can't assign to literal

The first example tries to assign the value 5 to the len() call. The SyntaxError message is very helpful in this case. It tells you that you can’t assign a value to a function call.

The second and third examples try to assign a string and an integer to literals. The same rule is true for other literal values. Once again, the traceback messages indicate that the problem occurs when you attempt to assign a value to a literal.

It’s likely that your intent isn’t to assign a value to a literal or a function call. For instance, this can occur if you accidentally leave off the extra equals sign (=), which would turn the assignment into a comparison. A comparison, as you can see below, would be valid:

>>>

>>> len('hello') == 5
True

Most of the time, when Python tells you that you’re making an assignment to something that can’t be assigned to, you first might want to check to make sure that the statement shouldn’t be a Boolean expression instead. You may also run into this issue when you’re trying to assign a value to a Python keyword, which you’ll cover in the next section.

Misspelling, Missing, or Misusing Python Keywords

Python keywords are a set of protected words that have special meaning in Python. These are words you can’t use as identifiers, variables, or function names in your code. They’re a part of the language and can only be used in the context that Python allows.

There are three common ways that you can mistakenly use keywords:

  1. Misspelling a keyword
  2. Missing a keyword
  3. Misusing a keyword

If you misspell a keyword in your Python code, then you’ll get a SyntaxError. For example, here’s what happens if you spell the keyword for incorrectly:

>>>

>>> fro i in range(10):
  File "<stdin>", line 1
    fro i in range(10):
        ^
SyntaxError: invalid syntax

The message reads SyntaxError: invalid syntax, but that’s not very helpful. The traceback points to the first place where Python could detect that something was wrong. To fix this sort of error, make sure that all of your Python keywords are spelled correctly.

Another common issue with keywords is when you miss them altogether:

>>>

>>> for i range(10):
  File "<stdin>", line 1
    for i range(10):
              ^
SyntaxError: invalid syntax

Once again, the exception message isn’t that helpful, but the traceback does attempt to point you in the right direction. If you move back from the caret, then you can see that the in keyword is missing from the for loop syntax.

You can also misuse a protected Python keyword. Remember, keywords are only allowed to be used in specific situations. If you use them incorrectly, then you’ll have invalid syntax in your Python code. A common example of this is the use of continue or break outside of a loop. This can easily happen during development when you’re implementing things and happen to move logic outside of a loop:

>>>

>>> names = ['pam', 'jim', 'michael']
>>> if 'jim' in names:
...     print('jim found')
...     break
...
  File "<stdin>", line 3
SyntaxError: 'break' outside loop

>>> if 'jim' in names:
...     print('jim found')
...     continue
...
  File "<stdin>", line 3
SyntaxError: 'continue' not properly in loop

Here, Python does a great job of telling you exactly what’s wrong. The messages "'break' outside loop" and "'continue' not properly in loop" help you figure out exactly what to do. If this code were in a file, then Python would also have the caret pointing right to the misused keyword.

Another example is if you attempt to assign a Python keyword to a variable or use a keyword to define a function:

>>>

>>> pass = True
  File "<stdin>", line 1
    pass = True
         ^
SyntaxError: invalid syntax

>>> def pass():
  File "<stdin>", line 1
    def pass():
           ^
SyntaxError: invalid syntax

When you attempt to assign a value to pass, or when you attempt to define a new function called pass, you’ll get a SyntaxError and see the "invalid syntax" message again.

It might be a little harder to solve this type of invalid syntax in Python code because the code looks fine from the outside. If your code looks good, but you’re still getting a SyntaxError, then you might consider checking the variable name or function name you want to use against the keyword list for the version of Python that you’re using.

The list of protected keywords has changed with each new version of Python. For example, in Python 3.6 you could use await as a variable name or function name, but as of Python 3.7, that word has been added to the keyword list. Now, if you try to use await as a variable or function name, this will cause a SyntaxError if your code is for Python 3.7 or later.

Another example of this is print, which differs in Python 2 vs Python 3:

Version print Type Takes A Value
Python 2 keyword no
Python 3 built-in function yes

print is a keyword in Python 2, so you can’t assign a value to it. In Python 3, however, it’s a built-in function that can be assigned values.

You can run the following code to see the list of keywords in whatever version of Python you’re running:

import keyword
print(keyword.kwlist)

keyword also provides the useful keyword.iskeyword(). If you just need a quick way to check the pass variable, then you can use the following one-liner:

>>>

>>> import keyword; keyword.iskeyword('pass')
True

This code will tell you quickly if the identifier that you’re trying to use is a keyword or not.

Missing Parentheses, Brackets, and Quotes

Often, the cause of invalid syntax in Python code is a missed or mismatched closing parenthesis, bracket, or quote. These can be hard to spot in very long lines of nested parentheses or longer multi-line blocks. You can spot mismatched or missing quotes with the help of Python’s tracebacks:

>>>

>>> message = 'don't'
  File "<stdin>", line 1
    message = 'don't'
                   ^
SyntaxError: invalid syntax

Here, the traceback points to the invalid code where there’s a t' after a closing single quote. To fix this, you can make one of two changes:

  1. Escape the single quote with a backslash ('don't')
  2. Surround the entire string in double-quotes instead ("don't")

Another common mistake is to forget to close string. With both double-quoted and single-quoted strings, the situation and traceback are the same:

>>>

>>> message = "This is an unclosed string
  File "<stdin>", line 1
    message = "This is an unclosed string
                                        ^
SyntaxError: EOL while scanning string literal

This time, the caret in the traceback points right to the problem code. The SyntaxError message, "EOL while scanning string literal", is a little more specific and helpful in determining the problem. This means that the Python interpreter got to the end of a line (EOL) before an open string was closed. To fix this, close the string with a quote that matches the one you used to start it. In this case, that would be a double quote (").

Quotes missing from statements inside an f-string can also lead to invalid syntax in Python:

 1# theofficefacts.py
 2ages = {
 3    'pam': 24,
 4    'jim': 24,
 5    'michael': 43
 6}
 7print(f'Michael is {ages["michael]} years old.')

Here, the reference to the ages dictionary inside the printed f-string is missing the closing double quote from the key reference. The resulting traceback is as follows:

$ python theofficefacts.py
  File "theofficefacts.py", line 7
    print(f'Michael is {ages["michael]} years old.')
         ^
SyntaxError: f-string: unterminated string

Python identifies the problem and tells you that it exists inside the f-string. The message "unterminated string" also indicates what the problem is. The caret in this case only points to the beginning of the f-string.

This might not be as helpful as when the caret points to the problem area of the f-string, but it does narrow down where you need to look. There’s an unterminated string somewhere inside that f-string. You just have to find out where. To fix this problem, make sure that all internal f-string quotes and brackets are present.

The situation is mostly the same for missing parentheses and brackets. If you leave out the closing square bracket from a list, for example, then Python will spot that and point it out. There are a few variations of this, however. The first is to leave the closing bracket off of the list:

# missing.py
def foo():
    return [1, 2, 3

print(foo())

When you run this code, you’ll be told that there’s a problem with the call to print():

$ python missing.py
  File "missing.py", line 5
    print(foo())
        ^
SyntaxError: invalid syntax

What’s happening here is that Python thinks the list contains three elements: 1, 2, and 3 print(foo()). Python uses whitespace to group things logically, and because there’s no comma or bracket separating 3 from print(foo()), Python lumps them together as the third element of the list.

Another variation is to add a trailing comma after the last element in the list while still leaving off the closing square bracket:

# missing.py
def foo():
    return [1, 2, 3,

print(foo())

Now you get a different traceback:

$ python missing.py
  File "missing.py", line 6

                ^
SyntaxError: unexpected EOF while parsing

In the previous example, 3 and print(foo()) were lumped together as one element, but here you see a comma separating the two. Now, the call to print(foo()) gets added as the fourth element of the list, and Python reaches the end of the file without the closing bracket. The traceback tells you that Python got to the end of the file (EOF), but it was expecting something else.

In this example, Python was expecting a closing bracket (]), but the repeated line and caret are not very helpful. Missing parentheses and brackets are tough for Python to identify. Sometimes the only thing you can do is start from the caret and move backward until you can identify what’s missing or wrong.

Mistaking Dictionary Syntax

You saw earlier that you could get a SyntaxError if you leave the comma off of a dictionary element. Another form of invalid syntax with Python dictionaries is the use of the equals sign (=) to separate keys and values, instead of the colon:

>>>

>>> ages = {'pam'=24}
  File "<stdin>", line 1
    ages = {'pam'=24}
                 ^
SyntaxError: invalid syntax

Once again, this error message is not very helpful. The repeated line and caret, however, are very helpful! They’re pointing right to the problem character.

This type of issue is common if you confuse Python syntax with that of other programming languages. You’ll also see this if you confuse the act of defining a dictionary with a dict() call. To fix this, you could replace the equals sign with a colon. You can also switch to using dict():

>>>

>>> ages = dict(pam=24)
>>> ages
{'pam': 24}

You can use dict() to define the dictionary if that syntax is more helpful.

Using the Wrong Indentation

There are two sub-classes of SyntaxError that deal with indentation issues specifically:

  1. IndentationError
  2. TabError

While other programming languages use curly braces to denote blocks of code, Python uses whitespace. That means that Python expects the whitespace in your code to behave predictably. It will raise an IndentationError if there’s a line in a code block that has the wrong number of spaces:

 1# indentation.py
 2def foo():
 3    for i in range(10):
 4        print(i)
 5  print('done')
 6
 7foo()

This might be tough to see, but line 5 is only indented 2 spaces. It should be in line with the for loop statement, which is 4 spaces over. Thankfully, Python can spot this easily and will quickly tell you what the issue is.

There’s also a bit of ambiguity here, though. Is the print('done') line intended to be after the for loop or inside the for loop block? When you run the above code, you’ll see the following error:

$ python indentation.py
  File "indentation.py", line 5
    print('done')
                ^
IndentationError: unindent does not match any outer indentation level

Even though the traceback looks a lot like the SyntaxError traceback, it’s actually an IndentationError. The error message is also very helpful. It tells you that the indentation level of the line doesn’t match any other indentation level. In other words, print('done') is indented 2 spaces, but Python can’t find any other line of code that matches this level of indentation. You can fix this quickly by making sure the code lines up with the expected indentation level.

The other type of SyntaxError is the TabError, which you’ll see whenever there’s a line that contains either tabs or spaces for its indentation, while the rest of the file contains the other. This might go hidden until Python points it out to you!

If your tab size is the same width as the number of spaces in each indentation level, then it might look like all the lines are at the same level. However, if one line is indented using spaces and the other is indented with tabs, then Python will point this out as a problem:

 1# indentation.py
 2def foo():
 3    for i in range(10):
 4        print(i)
 5    print('done')
 6
 7foo()

Here, line 5 is indented with a tab instead of 4 spaces. This code block could look perfectly fine to you, or it could look completely wrong, depending on your system settings.

Python, however, will notice the issue immediately. But before you run the code to see what Python will tell you is wrong, it might be helpful for you to see an example of what the code looks like under different tab width settings:

$ tabs 4 # Sets the shell tab width to 4 spaces
$ cat -n indentation.py
     1   # indentation.py
     2   def foo():
     3       for i in range(10)
     4           print(i)
     5       print('done')
     6   
     7   foo()

$ tabs 8 # Sets the shell tab width to 8 spaces (standard)
$ cat -n indentation.py
     1   # indentation.py
     2   def foo():
     3       for i in range(10)
     4           print(i)
     5           print('done')
     6   
     7   foo()

$ tabs 3 # Sets the shell tab width to 3 spaces
$ cat -n indentation.py
     1   # indentation.py
     2   def foo():
     3       for i in range(10)
     4           print(i)
     5      print('done')
     6   
     7   foo()

Notice the difference in display between the three examples above. Most of the code uses 4 spaces for each indentation level, but line 5 uses a single tab in all three examples. The width of the tab changes, based on the tab width setting:

  • If the tab width is 4, then the print statement will look like it’s outside the for loop. The console will print 'done' at the end of the loop.
  • If the tab width is 8, which is standard for a lot of systems, then the print statement will look like it’s inside the for loop. The console will print 'done' after each number.
  • If the tab width is 3, then the print statement looks out of place. In this case, line 5 doesn’t match up with any indentation level.

When you run the code, you’ll get the following error and traceback:

$ python indentation.py
  File "indentation.py", line 5
    print('done')
                ^
TabError: inconsistent use of tabs and spaces in indentation

Notice the TabError instead of the usual SyntaxError. Python points out the problem line and gives you a helpful error message. It tells you clearly that there’s a mixture of tabs and spaces used for indentation in the same file.

The solution to this is to make all lines in the same Python code file use either tabs or spaces, but not both. For the code blocks above, the fix would be to remove the tab and replace it with 4 spaces, which will print 'done' after the for loop has finished.

Defining and Calling Functions

You might run into invalid syntax in Python when you’re defining or calling functions. For example, you’ll see a SyntaxError if you use a semicolon instead of a colon at the end of a function definition:

>>>

>>> def fun();
  File "<stdin>", line 1
    def fun();
             ^
SyntaxError: invalid syntax

The traceback here is very helpful, with the caret pointing right to the problem character. You can clear up this invalid syntax in Python by switching out the semicolon for a colon.

In addition, keyword arguments in both function definitions and function calls need to be in the right order. Keyword arguments always come after positional arguments. Failure to use this ordering will lead to a SyntaxError:

>>>

>>> def fun(a, b):
...     print(a, b)
...
>>> fun(a=1, 2)
  File "<stdin>", line 1
SyntaxError: positional argument follows keyword argument

Here, once again, the error message is very helpful in telling you exactly what is wrong with the line.

Changing Python Versions

Sometimes, code that works perfectly fine in one version of Python breaks in a newer version. This is due to official changes in language syntax. The most well-known example of this is the print statement, which went from a keyword in Python 2 to a built-in function in Python 3:

>>>

>>> # Valid Python 2 syntax that fails in Python 3
>>> print 'hello'
  File "<stdin>", line 1
    print 'hello'
                ^
SyntaxError: Missing parentheses in call to 'print'. Did you mean print('hello')?

This is one of the examples where the error message provided with the SyntaxError shines! Not only does it tell you that you’re missing parenthesis in the print call, but it also provides the correct code to help you fix the statement.

Another problem you might encounter is when you’re reading or learning about syntax that’s valid syntax in a newer version of Python, but isn’t valid in the version you’re writing in. An example of this is the f-string syntax, which doesn’t exist in Python versions before 3.6:

>>>

>>> # Any version of python before 3.6 including 2.7
>>> w ='world'
>>> print(f'hello, {w}')
  File "<stdin>", line 1
    print(f'hello, {w}')
                      ^
SyntaxError: invalid syntax

In versions of Python before 3.6, the interpreter doesn’t know anything about the f-string syntax and will just provide a generic "invalid syntax" message. The problem, in this case, is that the code looks perfectly fine, but it was run with an older version of Python. When in doubt, double-check which version of Python you’re running!

Python syntax is continuing to evolve, and there are some cool new features introduced in Python 3.8:

  • Walrus operator (assignment expressions)
  • F-string syntax for debugging
  • Positional-only arguments

If you want to try out some of these new features, then you need to make sure you’re working in a Python 3.8 environment. Otherwise, you’ll get a SyntaxError.

Python 3.8 also provides the new SyntaxWarning. You’ll see this warning in situations where the syntax is valid but still looks suspicious. An example of this would be if you were missing a comma between two tuples in a list. This would be valid syntax in Python versions before 3.8, but the code would raise a TypeError because a tuple is not callable:

>>>

>>> [(1,2)(2,3)]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object is not callable

This TypeError means that you can’t call a tuple like a function, which is what the Python interpreter thinks you’re doing.

In Python 3.8, this code still raises the TypeError, but now you’ll also see a SyntaxWarning that indicates how you can go about fixing the problem:

>>>

>>> [(1,2)(2,3)]
<stdin>:1: SyntaxWarning: 'tuple' object is not callable; perhaps you missed a comma?
Traceback (most recent call last):   
  File "<stdin>", line 1, in <module>    
TypeError: 'tuple' object is not callable

The helpful message accompanying the new SyntaxWarning even provides a hint ("perhaps you missed a comma?") to point you in the right direction!

Conclusion

In this tutorial, you’ve seen what information the SyntaxError traceback gives you. You’ve also seen many common examples of invalid syntax in Python and what the solutions are to those problems. Not only will this speed up your workflow, but it will also make you a more helpful code reviewer!

When you’re writing code, try to use an IDE that understands Python syntax and provides feedback. If you put many of the invalid Python code examples from this tutorial into a good IDE, then they should highlight the problem lines before you even get to execute your code.

Getting a SyntaxError while you’re learning Python can be frustrating, but now you know how to understand traceback messages and what forms of invalid syntax in Python you might come up against. The next time you get a SyntaxError, you’ll be better equipped to fix the problem quickly!

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Identify Invalid Python Syntax

Ситуация: программист взял в работу математический проект — ему нужно написать код, который будет считать функции и выводить результаты. В задании написано:

«Пусть у нас есть функция f(x,y) = xy, которая перемножает два аргумента и возвращает полученное значение».

Программист садится и пишет код:

a = 10
b = 15
result = 0
def fun(x,y): 
    return x y
result = fun(a,b)
print(result)

Но при выполнении такого кода компьютер выдаёт ошибку:

File "main.py", line 13
result = x y
^
❌ SyntaxError: invalid syntax

Почему так происходит: в каждом языке программирования есть свой синтаксис — правила написания и оформления команд. В Python тоже есть свой синтаксис, по которому для умножения нельзя просто поставить рядом две переменных, как в математике. Интерпретатор находит первую переменную и думает, что ему сейчас объяснят, что с ней делать. Но вместо этого он сразу находит вторую переменную. Интерпретатор не знает, как именно нужно их обработать, потому что у него нет правила «Если две переменные стоят рядом, их нужно перемножить». Поэтому интерпретатор останавливается и говорит, что у него лапки. 

Что делать с ошибкой SyntaxError: invalid syntax

В нашем случае достаточно поставить звёздочку (знак умножения в Python) между переменными — это оператор умножения, который Python знает:

a = 10
b = 15
result = 0
def fun(x,y): 
    return x * y
result = fun(a,b)
print(result)

В общем случае найти источник ошибки SyntaxError: invalid syntax можно так:

  1. Проверьте, не идут ли у вас две команды на одной строке друг за другом.
  2. Найдите в справочнике описание команды, которую вы хотите выполнить. Возможно, где-то опечатка.
  3. Проверьте, не пропущена ли команда на месте ошибки.

Практика

Попробуйте найти ошибки в этих фрагментах кода:

x = 10 y = 15
def fun(x,y): 
    return x * y
try:  
    a = 100
    b = "PythonRu"
    assert a = b
except AssertionError:  
    print("Исключение AssertionError.")
else:  
    print("Успех, нет ошибок!")

Вёрстка:

Кирилл Климентьев

SyntaxError — это ошибка, которая легко может ввести в ступор начинающего программиста. Стоит забыть одну запятую или не там поставить кавычку и Python наотрез откажется запускать программу. Что ещё хуже, по выводу в консоль сложно сообразить в чём дело. Выглядят сообщения страшно и непонятно. Что с этим делать — не ясно. Вот неполный список того, что можно встретить:

  • SyntaxError: invalid syntax
  • SyntaxError: EOL while scanning string literal
  • SyntaxError: unexpected EOF while parsing

Эта статья о том, как справиться с синтаксической ошибкой SyntaxError. Дочитайте её до конца и получите безотказный простой алгоритм действий, что поможет вам в трудную минуту — ваш спасательный круг.

Работать будем с программой, которая выводит на экран список учеников. Её код выглядит немного громоздко и, возможно, непривычно. Если не всё написанное вам понятно, то не отчаивайтесь, чтению статьи это не помешает.


students = [
    ['Егор', 'Кузьмин'],
    ['Денис', 'Давыдов'],
]

for first_name, last_name in students:
    label = 'Имя ученика: {first_name} {last_name}'.format(
        first_name = first_name
        last_name = last_name
    )

    print(label)

Ожидается примерно такой результат в консоли:

$ python script.py
Имя ученика: Егор Кузьмин
Имя ученика: Денис Давыдов

Но запуск программы приводит к совсем другому результату. Скрипт сломан:

$ python script.py
  File "script.py", line 9
    last_name = last_name
            ^
SyntaxError: invalid syntax

Ошибки в программе бывают разные и каждой нужен свой особый подход. Первым делом внимательно посмотрите на вывод программы в консоль. На последней строчке написано SyntaxError: invalid syntax. Если эти слова вам не знакомы, то обратитесь за переводом к Яндекс.Переводчику:

SyntaxError: недопустимый синтаксис
SyntaxError: неверный синтаксис

Первое слово SyntaxError Яндекс не понял. Помогите ему и разделите слова пробелом:

Syntax Error: invalid syntax
Синтаксическая ошибка: неверный синтаксис

Теория. Синтаксические ошибки

Программирование — это не магия, а Python — не волшебный шар. Он не умеет предсказывать будущее, у него нет доступа к секретным знаниями, это просто автомат, это программа. Узнайте как она работает, как ищет ошибки в коде, и тогда легко найдете эффективный способ отладки. Вся необходимая теория собрана в этом разделе, дочитайте до конца.

SyntaxError — это синтаксическая ошибка. Она случается очень рано, еще до того, как Python запустит программу. Вот что делает компьютер, когда вы запускаете скрипт командой python script.py:

  1. запускает программу python
  2. python считывает текст из файла script.py
  3. python превращает текст программы в инструкции
  4. python исполняет инструкции

Синтаксическая ошибка SyntaxError возникает на четвёртом этапе в момент, когда Python разбирает текст программы на понятные ему компоненты. Сложные выражения в коде он разбирает на простейшие инструкции. Вот пример кода и инструкции для него:

person = {'name': 'Евгений'}

Инструкции:

  1. создать строку 'Евгений'
  2. создать словарь
  3. в словарь добавить ключ 'name' со значением 'Евгений'
  4. присвоить результат переменной person

SyntaxError случается когда Python не смог разбить сложный код на простые инструкции. Зная это, вы можете вручную разбить код на инструкции, чтобы затем проверить каждую из них по отдельности. Ошибка прячется в одной из инструкций.

1. Найдите поломанное выражение

Этот шаг сэкономит вам кучу сил. Найдите в программе сломанный участок кода. Его вам предстоит разобрать на отдельные инструкции. Посмотрите на вывод программы в консоль:

$ python script.py
  File "script.py", line 9
    last_name = last_name
            ^
SyntaxError: invalid syntax

Вторая строчка сообщает: File "script.py", line 9 — ошибка в файле script.py на девятой строчке. Но эта строка является частью более сложного выражения, посмотрите на него целиком:

label = 'Имя ученика: {first_name} {last_name}'.format(
    first_name = first_name
    last_name = last_name
)

«Девман» — авторская методика обучения программированию. Готовим к работе крутых программистов на Python. Станьте программистом, пройдите продвинутый курс Python.

2. Разбейте выражение на инструкции

В прошлых шагах вы узнали что сломан этот фрагмент кода:

label = 'Имя ученика: {first_name} {last_name}'.format(
    first_name = first_name
    last_name = last_name
)

Разберите его на инструкции:

  1. создать строку 'Имя ученика: {first_name} {last_name}'
  2. получить у строки метод format
  3. вызвать функцию с двумя аргументами
  4. результат присвоить переменной label

Так выделил бы инструкции программист, но вот Python сделать так не смог и сломался. Пора выяснить на какой инструкции нашла коса на камень.

Теперь ваша задача переписать код так, чтобы в каждой строке программы исполнялось не более одной инструкции из списка выше. Так вы сможете тестировать их по отдельности и облегчите себе задачу. Так выглядит отделение инструкции по созданию строки:

# 1. создать строку
template = 'Имя ученика: {first_name} {last_name}'

label = template.format(
    first_name = first_name
    last_name = last_name
)

Сразу запустите код, проверьте что ошибка осталась на прежнему месте. Приступайте ко второй инструкции:

# 1. создать строку
template = 'Имя ученика: {first_name} {last_name}'

# 2. получить у строки метод
format = template.format

label = format(
    first_name = first_name
    last_name = last_name
)

Строка format = template.format создает новую переменную format и кладёт в неё функцию. Да, да, это не ошибка! Python разрешает класть в переменные всё что угодно, в том числе и функции. Новая переменная переменная format теперь работает как обычная функция, и её можно вызвать: format(...).

Снова запустите код. Ошибка появится внутри format. Под сомнением остались две инструкции:

  1. вызвать функцию с двумя аргументами
  2. результат присвоить переменной label

Скорее всего, Python не распознал вызов функции. Проверьте это, избавьтесь от последней инструкции — от создания переменной label:

# 1. создать строку
template = 'Имя ученика: {first_name} {last_name}'

# 2. получить у строки метод
format = template.format

# 3. вызвать функцию
format(
    first_name = first_name
    last_name = last_name
)

Запустите код. Ошибка снова там же — внутри format. Выходит, код вызова функции написан с ошибкой, Python не смог его превратить в инструкцию.

3. Проверьте синтаксис вызова функции

Теперь вы знаете что проблема в коде, вызывающем функцию. Можно помедитировать еще немного над кодом программы, пройтись по нему зорким взглядом еще разок в надежде на лучшее. А можно поискать в сети примеры кода для сравнения.

Запросите у Яндекса статьи по фразе “Python синтаксис функции”, а в них поищите код, похожий на вызов format и сравните. Вот одна из первых статей в поисковой выдаче:

  • Функции в Python

Уверен, теперь вы нашли ошибку. Победа!

The Python SyntaxError occurs when the interpreter encounters invalid syntax in code. When Python code is executed, the interpreter parses it to convert it into bytecode. If the interpreter finds any invalid syntax during the parsing stage, a SyntaxError is thrown.

What Causes Invalid SyntaxError

Some of the most common causes of syntax errors in Python are:

  • Misspelled reserved keywords
  • Missing quotes
  • Missing required spaces
  • Missing operators
  • Invalid usage of blocks (e.g. if-else, loops)
  • Invalid variable declarations
  • Invalid function definitions or calls

Python Invalid SyntaxError Example

Here’s an example of a Python SyntaxError thrown due to missing quotes:

print(Hello World)

In the above example, since the string “Hello World” is attempted to be printed without using quotes, a SyntaxError is thrown:

File "test.py", line 1

    print(Hello World)

                ^

SyntaxError: invalid syntax

How to Fix Invalid SyntaxError in Python

To avoid syntax errors, IDEs that understand Python syntax can be used as they highlight the lines containing the problem. These issues can then be fixed before code is executed.

If a SyntaxError occurs after execution, the traceback can be inspected to detect where the issue exists in code

The traceback from the earlier example can be inspected to fix the issue:

File "test.py", line 1

    print(Hello World)

                ^

SyntaxError: invalid syntax

Here, it can be seen that the issue exists in line 1. When this line is inspected, it should be clear that the error occurred because of missing quotes in the string. When these missing quotes are added, the syntax issue is fixed:

print("Hello World")

The above code runs successfully and produces the correct output as expected:


Hello World

Track, Analyze and Manage Errors With Rollbar

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Python errors easier than ever. Try it today!

It’s a sadly unhelpful error message and it’s one that you’ll see quite often when learning Python.

What does SyntaxError: invalid syntax mean?
What is Python trying to tell you with this error and how can you fix your code to make Python happy?

What is a SyntaxError in Python?

This is Python’s way of saying «I don’t understand you».
Python knows that what you’ve typed isn’t valid Python code but it’s not sure what advice to give you.

When you’re lucky, your SyntaxError will have some helpful advice in it:

$ python3 greet.py
  File "/home/trey/greet.py", line 10
    if name == "Trey"
                     ^
SyntaxError: expected ':'

But if you’re unlucky, you’ll see the message invalid syntax with nothing more:

$ python3.9 greet.py
  File "/home/trey/greet.py", line 4
    name
    ^
SyntaxError: invalid syntax

This error message gives us no hints as to what might be going on outside of a line number and a bit of highlighting indicating where Python thinks the error occurred.

Causes of SyntaxError: invalid syntax

What are the likely causes of this mysterious error message?

When my Python students hit this error, the most likely causes are typically:

  1. Missing a colon (:) at the end of a line or mixing up other symbols
  2. Missing opening or closing parentheses (()), brackets ([]), braces ({}), or quotes ("")
  3. Misspelled or missing keywords or mistyping syntax within a block or expression
  4. Attempting to use a reserved keyword as a variable name
  5. Incorrectly indented code or other whitespace errors
  6. Treating statements like expressions
  7. Copying Python code into the REPL or copying from the REPL into a Python file

That’s a lot of options and they’re not the only options.
How should you approach fixing this problem?

Fixing SyntaxError: invalid syntax

The first step in fixing SyntaxErrors is narrowing down the problem.

I usually take the approach of:

  1. Note the line number and error message from the traceback, keeping in mind that both of these just guesses that Python’s making
  2. Working through the above list of common causes
  3. Attempting to read the code as Python would, looking for syntax mistakes
  4. Narrowing down the problem by removing blocks of code that I suspect may be the culprit

It’s easier to address that dreaded SyntaxError: invalid syntax exception when you’re familiar with its most common causes.
Let’s attempt to build up our intuitions around SyntaxError: invalid syntax by touring the common causes of this error message.

Upgrading Python improves error messages

Before diving into specific errors, note that upgrading your Python version can drastically improve the helpfulness of common error messages.

Take this error message:

$ python3 square.py
  File "/home/trey/square.py", line 2
    return [
    ^
SyntaxError: invalid syntax

On Python 3.10 it looks considerably different:

$ python3.10 square.py
  File "/home/trey/square.py", line 1
    def square_all(numbers:
                  ^
SyntaxError: '(' was never closed

We’re running the same square.py file in both cases:

def square_all(numbers:
    return [
        n**2
        for n in numbers
    ]

But Python 3.10 showed a much more helpful message: the line number, the position, and the error message itself are all much clearer for many unclosed parentheses and braces on Python 3.10 and above.

The dreaded missing colon is another example.
Any expression that starts a new block of code needs a : at the end.

Here’s the error that Python 3.9 shows for a missing colon:

$ python3 greet.py
  File "/home/trey/greet.py", line 10
    if name == "Trey"
                     ^
SyntaxError: invalid syntax

And here’s the same error in Python 3.10:

$ python3 greet.py
  File "/home/trey/greet.py", line 10
    if name == "Trey"
                     ^
SyntaxError: expected ':'

Much more helpful, right?
It’s still a SyntaxError exception, but the message is much clearer than simply invalid syntax.

Python 3.10 also includes friendlier error messages when you use = where you likely meant ==:

>>> name = "Trey"
>>> if name = "Trey":
  File "<stdin>", line 1
    if name = "Trey":
       ^^^^^^^^^^^^^
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?

Newer Python versions include more helpful error messages for missing commas, inline if expressions, unclosed braces/brackets/parentheses, and more.

If you have the ability to run your code on a newer version of Python, try it out.
It might help you troubleshoot your syntax errors more effectively.

Count your parentheses

Forgetting closing parentheses, brackets, and braces is also a common source of coding errors.

Fortunately, recent Python versions have started noting unclosed brackets in their SyntaxError messages.

When running this code:

def colors():
    c = ['red',
        'blue',
    return c

Python 3.9 used to show simply invalid syntax:

$ python3.9 colors.py
  File "/home/trey/colors.py", line 4
    return c
    ^
SyntaxError: invalid syntax

But Python 3.10 shows a more helpful error message:

$ python3.10 colors.py
  File "/home/trey/colors.py", line 2
    c = ['red',
        ^
SyntaxError: '[' was never closed

But sometimes Python can get a little confused when guessing the cause of an error.
Take this populate.py script:

import random
import names

random_list=["a1","a2","a3","b1","b2","b3","c1","c2","c3"]

with open("one.txt","w+") as one, 
     open("two.txt","w+") as two, 
     open("three.txt","w+") as three:
      for i in range(0,3):
          one.write("%sn" "%s" % (names.get_first_name(),
              random.choice(random_list))
          two.write("%sn" "%s" % (names.get_first_name(),
              random.choice(random_list))
          three.write("%sn" "%s" % (names.get_first_name(),
              random.choice(random_list))

When running this script, Python 3.10 shows this error message:

$ python3.10 populate.py
  File "/home/trey/populate.py", line 9
    one.write("%sn" "%s" %
              ^^^^^^^^^^^^^
SyntaxError: invalid syntax. Perhaps you forgot a comma?

The problem is that all 3 of those write method calls are missing closing parentheses.

Count your parentheses!

Many code editors highlight matching parentheses, brackets, and braces (when your cursor is at an opening parentheses the closing one will change color).
Use your code editor to see if each pair of parenthesis matches up properly (and that the one in matches seems correct).

Misspelled, missing, or misplaced keywords

Can you see what’s wrong with this line of code?

>>> drf sum_of_squares(numbers):
  File "<stdin>", line 1
    drf sum_of_squares(numbers):
        ^
SyntaxError: invalid syntax

We were trying to define a function, but we misspelled def as drf.
Python couldn’t figure out what we were trying to do, so it showed us that generic invalid syntax message.

What about this one?

>>> numbers = [2, 1, 3, 4, 7, 11, 18]
>>> squares = [n**2 for numbers]
  File "<stdin>", line 1
    squares = [n**2 for numbers]
                               ^
SyntaxError: invalid syntax

Python’s pointing to the end of our comprehension and saying there’s a syntax error.
But why?

Look a bit closer.
There’s something missing in our comprehension.

We meant type this:

>>> numbers = [2, 1, 3, 4, 7, 11, 18]
>>> squares = [n**2 for n in numbers]

We were missing the in in our comprehension’s looping component.

Misspelled keywords and missing keywords often result in that mysterious invalid syntax, but extra keywords can cause trouble as well.

You can’t use reserved words as variable names in Python:

>>> class = "druid"
  File "<stdin>", line 1
    class = "druid"
          ^
SyntaxError: invalid syntax

Python sees that word class and it assumes we’re defining a class.
But then it sees an = sign and gets confused and can’t tell what we’re trying to do, so it throws its hands in the error and yells invalid syntax!

This one is a bit more mysterious:

>>> import urlopen from urllib.request
  File "<stdin>", line 1
    import urlopen from urllib.request
                   ^^^^
SyntaxError: invalid syntax

That looks right, doesn’t it?
So what’s the problem?

In Python the importfrom syntax is actually a fromimport syntax.
We meant to write this instead:

>>> from urllib.request import urlopen

Watch out for misspelled keywords, missing keywords, and re-arranged syntax.
Also be sure not to use reserved words as variable names (e.g. class, return, and import are invalid variable names).

Subtle spacing problems

Can you see what’s wrong in this code?

>>> class Thing:
...     def __init _(self, name, color):
  File "<stdin>", line 2
    def __init _(self, name, color):
               ^
SyntaxError: invalid syntax

Notice the extra space in the function name (__init_ _ instead of __init__)?

Can you identify what’s wrong in this line?

>>> class Thing:
...     def__init__(self, name, color):
  File "<stdin>", line 2
    def__init__(self, name, color):
                                  ^
SyntaxError: invalid syntax

This one might be harder to spot.

Everything on that line is correct except that there’s no space between def and __init__.

When one space character is valid, you can usually use more than one space character as well.
But adding an extra space in the middle of an identifier or removing spaces where there should be spaces can often cause syntax errors.

Forgotten quotes and extra quotes

If you code infrequently, you likely forget to put quotes around your strings often.
This is a very common mistake, so rest assured that you’re not alone!

Forgotten quotes can sometimes result in this cryptic invalid syntax error message:

>>> print(Four!) if n
  File "<stdin>", line 1
    print(Four!) if n
              ^
SyntaxError: invalid syntax

Be careful with quotes within quotes:

>>> question = 'What's that?'
  File "<stdin>", line 1
    question = 'What's that?'
                     ^
SyntaxError: invalid syntax

You’ll need to switch to a different quote style (using double quotes for example) or escape those quotes.

Mixing up your symbols

Sometimes your syntax might look correct but you’ve actually confused one bit of syntax for another common bit of syntax.

That’s what happened here:

>>> things = {duck='purple', monkey='green'}
  File "<stdin>", line 1
    things = {duck='purple', monkey='green'}
              ^^^^^^^^^^^^^
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?

We’re trying to make a dictionary and we’ve accidentally used = instead of : to separate our key-value pairs.

Here’s another dictionary symbol mix up:

>>> states = [
...     'Oregon': 'OR',
  File "<stdin>", line 2
    'Oregon': 'OR',
            ^
SyntaxError: invalid syntax

It looks like we’re trying to define a dictionary, but we started with an open square bracket ([) instead of an open curly brace ({).

Another common syntax mistake is missing periods:

  File "/home/trey/file_info.py", line 15
    size = path.stat()st_size
                      ^^^^^^^
SyntaxError: invalid syntax

We’re trying to access the st_size attribute on the object returned from that path.stat() call, but we’ve forgot to put a . before st_size.

Sometimes syntax errors are due to characters being swapped around:

>>> name = "Trey"
>>> name[]0
  File "<stdin>", line 1
    name[]0
         ^
SyntaxError: invalid syntax

And some syntax errors are due to extra symbols you didn’t intend to write:

>>> name = "Trey"
>>> name.lower.()
  File "<stdin>", line 1
    name.lower.()
               ^
SyntaxError: invalid syntax

We wrote an extra . before our parentheses above.

Indentation errors in disguise

Sometimes a SyntaxError is actually an indentation error in disguise.

For example this code has an else clause that’s too far indented:

import sys

name = sys.argv[1]

if name == "Trey":
    print("I know you")
    print("Your name is Troy... no, Trent? Trevor??")
    else:
        print("Hello stranger")

When we run the code we’ll see a SyntaxError:

$ python greet.py
  File "/home/trey/greet.py", line 8
    else:
    ^^^^
SyntaxError: invalid syntax

Indentation issues often result in IndentationError exceptions, but sometimes they’ll manifest as SyntaxError exceptions instead.

Embedding statements within statements

A «statement» is either a block of Python code or a single line of Python code that can stand on its own.

An «expression» is a chunk of Python code that evaluates to a value.
Expressions contain identifiers (i.e. variables), literals (e.g. [1, 2], "hi", and 4), and operators (e.g. +, in, and *).

In Python we can embed one expression within another.
But some expressions are actually «statements» which must be a line all on their own.

Here we’ve tried to embed one statement within another:

>>> def square_all(numbers):
...     return result = [n**2 for n in numbers]
  File "<stdin>", line 2
    return result = [n**2 for n in numbers]
                  ^
SyntaxError: invalid syntax

Assignments are statements in Python (result = ... is a statement).
Python’s return is also a statement.
We’ve tried to embed one statement inside another and Python didn’t understand us.

We likely meant either this:

def square_all(numbers):
    result = [n**2 for n in numbers]
    return result

Or this:

def square_all(numbers):
    return [n**2 for n in numbers]

Here’s the same issue with the global statement (see assigning to global variables):

>>> def connect(*args, **kwargs):
...     global _connection = sqlite3.connect(*args, **kwargs)
  File "<stdin>", line 2
    global _connection = sqlite3.connect(*args, **kwargs)
                       ^
SyntaxError: invalid syntax

And the same issue with the del statement:

trey_count = del counts['Trey']
  File "<stdin>", line 1
    trey_count = del counts['Trey']
                 ^^^
SyntaxError: invalid syntax

If assignment is involved in your statement-inside-a-statement, an assignment expression (via Python’s walrus operator) may be helpful in resolving your issue.
Though often the simplest solution is to split your code into multiple statements over multiple lines.

Errors that appear only in the Python REPL

Some errors are a bit less helpful within the Python REPL.

Take this invalid syntax error:

def square_all(numbers:
    return [
  File "<stdin>", line 2
    return [
    ^^^^^^
SyntaxError: invalid syntax

We’ll see that error within the Python REPL even on Python 3.11.

The issue is that the first line doesn’t have a closing parentheses.
Python 3.10+ would properly point this out if we ran our code from a .py file instead:

$ python3.10 square.py
  File "/home/trey/square.py", line 1
    def square_all(numbers:
                  ^
SyntaxError: '(' was never closed

But at the REPL Python doesn’t parse our code the same way (it parses block-by-block in the REPL) and sometimes error messages are a bit less helpful within the REPL as a result.

Here’s another REPL-specific error:

>>> def greet(name):
...     print(f"Howdy {name}!")
... greet("Trey")
  File "<stdin>", line 3
    greet("Trey")
    ^^^^^
SyntaxError: invalid syntax

This is valid Python code:

def greet(name):
    print(f"Howdy {name}!")
greet("Trey")

But that can’t be copy-pasted directly into the REPL.
In the Python REPL a blank line is needed after a block of code to end that block.

So we’d need to put a newline between the function definition and the function call:

>>> def greet(name):
...     print(f"Howdy {name}!")
...
>>> greet("Trey")
Howdy Trey!

Some errors are due to code that feels like it should work in a Python REPL but doesn’t.
For example running python from within your Python REPL doesn’t work:

>>> python greet.py
  File "<stdin>", line 1
    python greet.py
           ^^^^^
SyntaxError: invalid syntax
>>> python -m pip install django
  File "<stdin>", line 1
    python -m pip install django
              ^^^
SyntaxError: invalid syntax

The above commands would work from our system command-prompt, but they don’t work within the Python REPL.

If you’re trying to launch Python or send a command to your prompt outside Python (like ls or dir), you’ll need to do it from your system command prompt (Terminal, Powershell, Command Prompt, etc.).
You can only type valid Python code from within the Python REPL.

Problems copy-pasting from the REPL

Copy-pasting from the Python REPL into a .py file will also result in syntax errors.

Here’s we’re running a file that has >>> prefixes before each line:

$ python numbers.py
  File "/home/trey/numbers.py", line 1
    >>> n = 4
    ^^
SyntaxError: invalid syntax

This isn’t a valid Python program:

>>> n = 4
>>> print(n**2)

But this is a valid Python program:

You’ll need to be careful about empty lines when copy-pasting from a .py file into a Python REPL and you’ll need to be careful about >>> and ... prefixes and command output when copy-pasting from a REPL into a .py file.

The line number is just a «best guess»

It used to be that the line number for an error would usually represent the place that Python got confused about your syntax.
That line number was often one or more lines after the actual error.

In recent versions of Python, the core developers have updated these line numbers in an attempt to make them more accurate.

For example here’s an error on Python 3.9 due to a missing comma:

$ python3.9 greet.py
  File "/home/trey/greet.py", line 4
    name
    ^
SyntaxError: invalid syntax

And here’s the same error in Python 3.10:

$ python3.10 greet.py
  File "/home/greet.py", line 3
    "Hello there"
    ^^^^^^^^^^^^^
SyntaxError: invalid syntax. Perhaps you forgot a comma?

Python’s given us a helpful hint on Python 3.10.
But it’s also made a different guess about what line the error is on.

As you can see from the greet.py file, line 3 ("Hello there") is the better guess in this case, as that’s where the comma is needed.

def greet(name):
    print(
        "Hello there"
        name
    )

While deciphering tracebacks, keep in mind that the line number is just Python’s best guess as to where the error occurred.

SyntaxError exceptions happen all the time

If your code frequently results in SyntaxError exceptions, don’t fret.
These kinds of exceptions happen all the time.
When you’re newer to Python, you’ll find that it’s often a challenge to remember the exact syntax for the statements you’re writing.

But more experienced Python programmers also experience syntax errors.
I make typos in my code quite often.
I have a linter installed in my text editor to help me catch those typos though.
I recommend searching for a «Python» or «Python linter» extension for your favorite code editor so you can spot these issues quickly every time you save your .py files.

Once you get past syntax errors, you’ll likely hit other types of exceptions. Watch the exception screencast series for more on reading tracebacks and exception handling in Python.

Понравилась статья? Поделить с друзьями:
  • Sveba dahlen ошибка e5
  • Synsoacc dll cubase ошибка
  • Svchost ошибка приложения память не может быть read
  • Synology проверка сетевой среды ошибка
  • Svchost ошибка при запуске приложения 0xc0000007b