In computer science, a syntax error is an error in the syntax of a sequence of characters or tokens that is intended to be written in a particular programming language.
For compiled languages, syntax errors are detected at compile-time. A program will not compile until all syntax errors are corrected. For interpreted languages, however, a syntax error may be detected during program execution, and an interpreter’s error messages might not differentiate syntax errors from errors of other kinds.
There is some disagreement as to just what errors are «syntax errors». For example, some would say that the use of an uninitialized variable’s value in Java code is a syntax error, but many others would disagree[1][2] and would classify this as a (static) semantic error.
In 8-bit home computers that used BASIC interpreter as their primary user interface, the SYNTAX ERROR error message became somewhat notorious, as this was the response to any command or user input the interpreter could not parse.
A syntax error can occur or take place, when an invalid equation is being typed on a calculator. This can be caused, for instance, by opening brackets without closing them, or less commonly, entering several decimal points in one number.
In Java the following is a syntactically correct statement:
-
System.out.println("Hello World");
while the following is not:
-
System.out.println(Hello World);
The second example would theoretically print the variable Hello World instead of the words «Hello World». However, a variable in Java cannot have a space in between, so the syntactically correct line would be System.out.println(Hello_World).
A compiler will flag a syntax error when given source code that does not meet the requirements of the language’s grammar.
Type errors (such as an attempt to apply the ++ increment operator to a boolean variable in Java) and undeclared variable errors are sometimes considered to be syntax errors when they are detected at compile-time. However, it is common to classify such errors as (static) semantic errors instead.[2][3][4]
Syntax errors on calculatorsEdit
Syntax error in a scientific calculator
A syntax error is one of several types of errors on calculators (most commonly found on scientific calculators and graphing calculators), representing that the equation that has been input has incorrect syntax of numbers, operations and so on. It can result in various ways, including but not limited to:
- An open bracket without closing parenthesis (unless missing closing parenthesis is at very end of equation)
- Using minus sign instead of negative symbol (or vice versa), which are distinct on most scientific calculators. Note that while some scientific calculators allow a minus sign to stand in for a negative symbol, the reverse is less common.
See alsoEdit
- Tag soup
ReferencesEdit
- ^ Issue of syntax or semantics?
- ^ a b Semantic Errors in Java
- ^ Aho, Alfred V.; Monica S. Lam; Ravi Sethi; Jeffrey D. Ullman (2007). Compilers: Principles, Techniques, and Tools (2nd ed.). Addison Wesley. ISBN 978-0-321-48681-3. Section 4.1.3: Syntax Error Handling, pp.194–195.
- ^ Louden, Kenneth C. (1997). Compiler Construction: Principles and Practice. Brooks/Cole. ISBN 981-243-694-4. Exercise 1.3, pp.27–28.
SyntaxError — это ошибка, которая легко может ввести в ступор начинающего программиста. Стоит забыть одну запятую или не там поставить кавычку и Python наотрез откажется запускать программу. Что ещё хуже, по выводу в консоль сложно сообразить в чём дело. Выглядят сообщения страшно и непонятно. Что с этим делать — не ясно. Вот неполный список того, что можно встретить:
SyntaxError: invalid syntaxSyntaxError: EOL while scanning string literalSyntaxError: 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:
- запускает программу
python pythonсчитывает текст из файлаscript.pypythonпревращает текст программы в инструкцииpythonисполняет инструкции
Синтаксическая ошибка SyntaxError возникает на четвёртом этапе в момент, когда Python разбирает текст программы на понятные ему компоненты. Сложные выражения в коде он разбирает на простейшие инструкции. Вот пример кода и инструкции для него:
person = {'name': 'Евгений'}
Инструкции:
- создать строку
'Евгений' - создать словарь
- в словарь добавить ключ
'name'со значением'Евгений' - присвоить результат переменной
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
)
2. Разбейте выражение на инструкции
В прошлых шагах вы узнали что сломан этот фрагмент кода:
label = 'Имя ученика: {first_name} {last_name}'.format(
first_name = first_name
last_name = last_name
)
Разберите его на инструкции:
- создать строку
'Имя ученика: {first_name} {last_name}' - получить у строки метод
format - вызвать функцию с двумя аргументами
- результат присвоить переменной
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. Под сомнением остались две инструкции:
- вызвать функцию с двумя аргументами
- результат присвоить переменной
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 SyntaxError object represents an error when trying to interpret syntactically invalid code. It is thrown when the JavaScript engine encounters tokens or token order that does not conform to the syntax of the language when parsing code.
SyntaxError is a serializable object, so it can be cloned with structuredClone() or copied between Workers using postMessage().
Constructor
SyntaxError()-
Creates a new
SyntaxErrorobject.
Instance properties
SyntaxError.prototype.message-
Error message. Inherited from
Error. SyntaxError.prototype.name-
Error name. Inherited from
Error. SyntaxError.prototype.cause-
Error cause. Inherited from
Error. SyntaxError.prototype.fileName
Non-standard
-
Path to file that raised this error. Inherited from
Error. SyntaxError.prototype.lineNumber
Non-standard
-
Line number in file that raised this error. Inherited from
Error. SyntaxError.prototype.columnNumber
Non-standard
-
Column number in line that raised this error. Inherited from
Error. SyntaxError.prototype.stack
Non-standard
-
Stack trace. Inherited from
Error.
Examples
Catching a SyntaxError
try {
eval("hoo bar");
} catch (e) {
console.error(e instanceof SyntaxError);
console.error(e.message);
console.error(e.name);
console.error(e.fileName);
console.error(e.lineNumber);
console.error(e.columnNumber);
console.error(e.stack);
}
Creating a SyntaxError
try {
throw new SyntaxError("Hello", "someFile.js", 10);
} catch (e) {
console.error(e instanceof SyntaxError); // true
console.error(e.message); // Hello
console.error(e.name); // SyntaxError
console.error(e.fileName); // someFile.js
console.error(e.lineNumber); // 10
console.error(e.columnNumber); // 0
console.error(e.stack); // @debugger eval code:3:9
}
Specifications
| Specification |
|---|
| ECMAScript Language Specification # sec-native-error-types-used-in-this-standard-syntaxerror |
Browser compatibility
BCD tables only load in the browser
See also
Ситуация: программист взял в работу математический проект — ему нужно написать код, который будет считать функции и выводить результаты. В задании написано:
«Пусть у нас есть функция 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 можно так:
- Проверьте, не идут ли у вас две команды на одной строке друг за другом.
- Найдите в справочнике описание команды, которую вы хотите выполнить. Возможно, где-то опечатка.
- Проверьте, не пропущена ли команда на месте ошибки.
Практика
Попробуйте найти ошибки в этих фрагментах кода:
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("Успех, нет ошибок!")
Вёрстка:
Кирилл Климентьев
Syntax and runtime errors always produce error messages. Reading and
understanding error messages is a crucial first step in fixing these types of
bugs.
Error messages are your friends. This idea can seem foreign to new
programmers, because an error message is a signal that your program is broken.
When we are working with a broken program, we might feel frustrated, like we do
not fully understand the concepts at hand.
However, the reality is that all programmers, no matter how experienced,
regularly make simple mistakes. If you run your program and it produces an
error message, your first reaction should be, «Great! My program has an error,
but I have a helpful message to help me fix it.»
Let’s consider a small program with a couple of syntax errors.
Example
let name = Julie;
console.log("Hello, name);
While you can spot one or more errors just by looking at the code, let’s
examine the error messages produced.
6.3.1. A Syntax Error¶
Running the program at this stage results in the message:
/Users/chris/dev/sandbox/js/syntax.js:2
console.log("Hello, name);
^^^^^^^^^^^^^^
SyntaxError: Invalid or unexpected token
at new Script (vm.js:85:7)
at createScript (vm.js:266:10)
at Object.runInThisContext (vm.js:314:10)
at Module._compile (internal/modules/cjs/loader.js:698:28)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:749:10)
at Module.load (internal/modules/cjs/loader.js:630:32)
at tryModuleLoad (internal/modules/cjs/loader.js:570:12)
at Function.Module._load (internal/modules/cjs/loader.js:562:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:801:12)
at internal/main/run_main_module.js:21:11
While there is a lot of text in this message, the first few lines tell us
everything we need to know.
The first portion identifies where in our code the error exists:
console.log("Hello, name);
^^^^^^^^^^^^^^
For many simple syntax errors, we will quickly be able to spot the mistake once
JavaScript points out its location to us.
If knowing the location of the error isn’t enough, the next line provides more
information:
SyntaxError: Invalid or unexpected token
This line identifies that actual issue that JavaScript found. It makes it clear
that we are dealing with a SyntaxError, and it provides a message that
describes the issue.
If you are scratching your head at the message, «Invalid or unexpected token,»
don’t worry. Programming languages often report errors in ways that are not
always easy to decipher at first glance. However, a second look at the line in
question helps us make sense of this message.
console.log("Hello, name);
^^^^^^^^^^^^^^
JavaScript is telling us that in the area of "Hello, name); it encountered
an invalid token. Token is a fancy word that means a symbol, variable, or
other atomic element of a program. In this case, the invalid token is "Hello,. JavaScript sees the double-quote character and expects a string.
name);
However, the string does not have a closing ", making it invalid.
Fixing this error gives us a program with correct syntax:
let name = Julie; console.log("Hello", name); |
Note
Error messages may differ depending on where you run your code. The same program run in a repl.it and Node.js on your computer will generate slightly different error messages. However, these differences are minor and generally unimportant. The main cause of the error will be reported in the same way.
6.3.2. Syntax Errors and Code Highlighting¶
Most code editors provide a feature known as syntax highlighting. Such
editors highlight different types of tokens in different ways. For example,
strings may be red, while variables may be green. This useful feature gives you
a quick, visual way to identify syntax errors.
For example, here is a screenshot of our flawed code taken within an editor at repl.it.
Screenshot of a program with two syntax errors¶
Notice that the string Hello is colored red, while most of the symbols
(=, ;, ., and () are colored black. At the end of line 2,
however, the final ) and ; are both red rather than black. Since we
haven’t closed the string, the editor assumes that these two symbols are part
of the string. Since we expect ); to be black in this editor, the
difference in color is a clue that something is wrong with our syntax.
6.3.3. A Runtime Error¶
Having fixed the syntax error, we can now run our program again. Doing so displays yet another error.
Hello
/Users/chris/dev/sandbox/js/syntax.js:1
let name = Julie;
^
ReferenceError: Julie is not defined
at Object.<anonymous> (/Users/chris/dev/sandbox/js/syntax.js:1:74)
at Module._compile (internal/modules/cjs/loader.js:738:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:749:10)
at Module.load (internal/modules/cjs/loader.js:630:32)
at tryModuleLoad (internal/modules/cjs/loader.js:570:12)
at Function.Module._load (internal/modules/cjs/loader.js:562:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:801:12)
at internal/main/run_main_module.js:21:11
We have a new error message, this time involving line 1 of our code. We didn’t see this error before because it is a runtime error. Due to the syntax error on line 2, the program stopped during the parsing phase. Even though the current error involves the line before the original syntax error, the syntax error still gets reported first.
Once again, we are told where the error occurs:
There appears to be an issue with the assignment statement. You might be able to see what it is, but let’s inspect the error message anyway. Doing so will help us understand JavaScript errors more generally.
The message is:
ReferenceError: Julie is not defined
The type of error is ReferenceError. If we search the web for «JS ReferenceError» then one of the first results is the MDN documentation for ReferenceError. No need to read the entire document, however. The first sentence on this page tells us what we need to know:
The
ReferenceErrorobject represents an error when a non-existent variable is referenced.
This information, along with the rest of the message, «Julie is not defined,» makes it clear what JavaScript is complaining about. The error message is saying, Hey, check your variables!
To us, we see that we forgot to enclose the string Julie in quotes, because we know that we intended to assign the variable name a string value. However, to JavaScript there is nothing in the program to indicate that Julie should be a string. In fact, JavaScript sees Julie as a variable. Since there is no such defined variable in our program, it returns a ReferenceError.
This is one of many examples when we, as humans, describe the same error slightly differently than JavaScript. Usually, neither description is better than the other. Humans and computers simply view information differently.

