Ситуация: программист взял в работу математический проект — ему нужно написать код, который будет считать функции и выводить результаты. В задании написано:
«Пусть у нас есть функция 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("Успех, нет ошибок!")
Вёрстка:
Кирилл Климентьев
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
Уверен, теперь вы нашли ошибку. Победа!
Содержание
- Python ImportError
- Python Certification Course
- Programming Languages Courses
- Angular JS Certification Training
- Introduction to Python ImportError
- Examples of ImporError in Python
- Example #1
- Example #2
- Example #3
- Conclusion – Python ImportError
- Recommended Articles
- Invalid Syntax in Python: Common Reasons for SyntaxError
- Invalid Syntax in Python
- SyntaxError Exception and Traceback
- Common Syntax Problems
- Misusing the Assignment Operator ( = )
- Misspelling, Missing, or Misusing Python Keywords
- Missing Parentheses, Brackets, and Quotes
- Mistaking Dictionary Syntax
- Using the Wrong Indentation
- Defining and Calling Functions
- Changing Python Versions
- Conclusion
Python ImportError
By
Abhilasha Chougule
Python Tutorial
Python Certification Course
Programming Languages Courses
Angular JS Certification Training

Introduction to Python ImportError
In Python, we use “import” when we want to import any specific module in the Python program. In Python, to make or to allow the module contents available to the program we use import statements. Therefore when importing any module and there is any trouble in importing modules to the program then there is a chance of ImportError occurrence. In this article, we will discuss such error which generally occurs if there is an invalid declaration of import statement for module importing and such problems also known as ModuleNotFoundError in the latest versions of Python such as 3.6 and newer versions.
Examples of ImporError in Python
In Python, when we want to include the module contents in the program then we have to import these specific modules in the program. So to do this we use “import” keyword such as import statement with the module name. When writing this statement and the specified module is not written properly or the imported module is not found in the Python library then the Python interpreter throws an error known as ImportError.
Web development, programming languages, Software testing & others








There are two conditions when the ImportError will be raised. They are
- If the module does not exist.
- If we are trying to import submodule from the module
Now let us demonstrate in the below program that throws an ImportError.
Example #1
Now suppose we are trying to import module “request” which is not present or saved in Python drive where we need to download it. Let us see a small example below:
Output:

In the above sample code, we can see that we are importing a module named “request” which is not present in the downloaded Python library. Therefore it throws an ImportError which gives the message saying no module named “request”. As each module when downloaded or inbuilt it has its own private symbol table where all defined module is saved by creating separate namespace. Therefore if the module is present then there is no occurrence of such error.
In Python, there is another way of importing modules in the program and if this statement also fails then also ImportError occurs. Let us see the example below:
Example #2
Output:

In the above program, we can see another way of importing modules. This also throws ImportError if the module is not present in the private Python library.
The above two methods of importing modules in the program throw an error if the module is not present. Therefore catch such errors in exception handling concept it provides an ImportError exception which has the Python exception hierarchy as BaseException, Exception, and then comes ImportError. In Python, even moduleNotFoundError is also the same as an ImportError exception. Now let us below how to handle such error in the Python program using try and except blocks of exception handling.
Example #3
Output:

In the above program, we can see when we are trying to import the “crypt” module and we are handling this ImportError using try and except the block of exception handling. This is one way to avoid the error message to be printed.
To avoid such an ImportError exception we saw above the use of exception handling. But still, it will display the error message on the output screen. Such error occurs when there is no module present in the Python private table. To avoid this we can directly download this module from the Internet to the Python IDE. Let us see how we can avoid this ImportError we need to download the module and we will not get this error and this done as below:
If pip is installed we can directly run this to install the module. Else first we need to install the pip and then install the other packages.
Another way to download the module is to download the package directly through the Internet by downloading the module and unzip the folder and save that folder where the Python software is saved.
Conclusion – Python ImportError
In this article, we conclude that the ImportError is an exception in Python hierarchy under BaseException, Exception, and then comes this Exception. In Python, ImportError occurs when the Python program tries to import module which does not exist in the private table. This exception can be avoided using exception handling using try and except blocks. We also saw examples of how the ImportError occurs and how it is handled.
Recommended Articles
This is a guide to Python ImportError. Here we also discuss the introduction and working of import error in python along with its different examples and its code implementation. You may also have a look at the following articles to learn more –
Источник
Invalid Syntax in Python: Common Reasons for SyntaxError
Table of Contents
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
Free Bonus: 5 Thoughts On Python Mastery, a free course for Python developers that shows you the roadmap and the mindset you’ll need to take your Python skills to the next level.
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.
Note: If your code is syntactically correct, then you may get other exceptions raised that are not a SyntaxError . To learn more about Python’s other exceptions and how to handle them, check out Python Exceptions: An Introduction.
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:
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:
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.
Note: This tutorial assumes that you know the basics of Python’s tracebacks. To learn more about the Python traceback and how to read them, check out Understanding the Python Traceback and Getting the Most out of a Python Traceback.
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:
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:
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.
Note: The examples above are missing the repeated code line and caret ( ^ ) pointing to the problem in the traceback. The exception and traceback you see will be different when you’re in the REPL vs trying to execute this code from a file. If this code were in a file, then you’d get the repeated code line and caret pointing to the problem, as you saw in other cases throughout this tutorial.
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:
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:
- Misspelling a keyword
- Missing a keyword
- 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:
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:
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:
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:
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:
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:
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:
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:
- Escape the single quote with a backslash ( ‘don’t’ )
- 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:
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:
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 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:
When you run this code, you’ll be told that there’s a problem with the call to print() :
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:
Now you get a different traceback:
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:
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() :
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:
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:
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:
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:
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:
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:
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:
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 :
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:
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:
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:
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:
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:
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
Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

About Chad Hansen

Chad is an avid Pythonista and does web development with Django fulltime. Chad lives in Utah with his wife and six kids.
Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:



![]()

Master Real-World Python Skills With Unlimited Access to Real Python
Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:
Master Real-World Python Skills
With Unlimited Access to Real Python
Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:
What Do You Think?
What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.
Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students. Get tips for asking good questions and get answers to common questions in our support portal. Looking for a real-time conversation? Visit the Real Python Community Chat or join the next “Office Hours” Live Q&A Session. Happy Pythoning!
Related Tutorial Categories: basics python
Источник
Программирование, Python, Учебный процесс в IT, Блог компании SkillFactory
Рекомендация: подборка платных и бесплатных курсов PR-менеджеров — https://katalog-kursov.ru/

Выяснить, что означают сообщения об ошибках Python, может быть довольно сложно, когда вы впервые изучаете язык. Вот список распространенных ошибок, которые приводят к сообщениям об ошибках во время выполнения, которые могут привести к сбою вашей программы.
1) Пропуск “:” после оператора if, elif, else, for, while, class или def. (Сообщение об ошибке: “SyntaxError: invalid syntax”)
Пример кода с ошибкой:
if spam == 42
print('Hello!')
2) Использование = вместо ==. (Сообщение об ошибке: “SyntaxError: invalid syntax”)
= является оператором присваивания, а == является оператором сравнения «равно». Пример кода с ошибкой:
if spam = 42:
print('Hello!')
3) Использование неправильного количества отступов. (Сообщение об ошибке: «IndentationError: unexpected indent» и «IndentationError: unindent does not match any outer indentation level» и «IndentationError: expected an indented block»)
Помните, что отступ увеличивается только после оператора, оканчивающегося на “:” двоеточие, и впоследствии должен вернуться к предыдущему отступу.
Пример кода с ошибкой:
print('Hello!')
print('Howdy!')
… еще:
if spam == 42:
print('Hello!')
print('Howdy!')
… еще:
if spam == 42:
print('Hello!')
4) Забыть вызвать len() в операторе цикла for. (Сообщение об ошибке: “TypeError: 'list' object cannot be interpreted as an integer”)
Обычно вы хотите перебирать индексы элементов в списке или строке, что требует вызова функции range(). Просто не забудьте передать возвращаемое значение len(someList) вместо передачи только someList.
Пример кода с ошикой:
spam = ['cat', 'dog', 'mouse']
for i in range(spam):
print(spam[i])
(UPD: как некоторые указали, вам может понадобиться только for i in spam: вместо приведенного выше кода. Но вышесказанное относится к очень законному случаю, когда вам нужен индекс в теле цикла, а не только само значение.)
5) Попытка изменить строковое значение. (Сообщение об ошибке: “TypeError: 'str' object does not support item assignment”)
Строки являются неизменным типом данных. Пример кода с ошибкой:
spam = 'I have a pet cat.'
spam[13] = 'r'
print(spam)
Пример правильного варианта:
spam = 'I have a pet cat.'
spam = spam[:13] + 'r' + spam[14:]
print(spam)
6) Попытка объединить не строковое значение в строковое значение. (Сообщение об ошибке: “TypeError: Can't convert 'int' object to str implicitly”)
Пример кода с ошибкой:
numEggs = 12
print('I have ' + numEggs + ' eggs.')
Правильный вариант:
numEggs = 12
print('I have ' + str(numEggs) + ' eggs.')
… или:
numEggs = 12
print('I have %s eggs.' % (numEggs))
7) Пропуск кавычки, в начале или конце строкового значения. (Сообщение об ошибке: “SyntaxError: EOL while scanning string literal”)
Пример кода с ошикой:
print(Hello!')
… еще:
print('Hello!)
...еще:
myName = 'Al'
print('My name is ' + myName + . How are you?')
8) Опечатка в переменной или имени функции. (Сообщение об ошибке: “NameError: name 'fooba' is not defined”)
Пример кода с ошибкой:
foobar = 'Al'
print('My name is ' + fooba)
...еще:
spam = ruond(4.2)
...еще:
spam = Round(4.2)
9) Опечатка в названии метода. (Сообщение об ошибке: “AttributeError: 'str' object has no attribute 'lowerr'”)
Пример кода с ошибкой:
spam = 'THIS IS IN LOWERCASE.'
spam = spam.lowerr()
10) Выход за пределы массива. (Сообщение об ошибке: “IndexError: list index out of range”)
Пример кода с ошибкой:
spam = ['cat', 'dog', 'mouse']
print(spam[6])
11) Использование несуществующего ключа словаря. (Сообщение об ошибке: “KeyError: 'spam'”)
Пример кода с ошибкой:
spam = {'cat': 'Zophie', 'dog': 'Basil', 'mouse': 'Whiskers'}
print('The name of my pet zebra is ' + spam['zebra'])
12) Попытка использовать ключевые слова Python в качестве переменной (Сообщение об ошибке: “SyntaxError: invalid syntax”)
Ключевые слова Python (также называются зарезервированные слова) не могут быть использованы для названия переменных. Ошибка будет со следующим кодом:
class = 'algebra'
Ключевые слова Python 3: and, as, assert, break, class, continue, def, del, elif, else, except, False, finally, for, from, global, if, import, in, is, lambda, None, nonlocal, not, or, pass, raise, return, True, try, while, with, yield
13) Использование расширенного оператора присваивания для новой переменной. (Сообщение об ошибке: “NameError: name 'foobar' is not defined”)
Не думайте, что переменные начинаются со значения, такого как 0 или пустая строка. Выражение с расширенным оператором как spam += 1 эквивалентно spam = spam + 1. Это означает, что для начала в spam должно быть какое-то значение.
Пример кода с ошибкой:
spam = 0
spam += 42
eggs += 42
14) Использование локальных переменных (с таким же именем как и у глобальной переменной) в функции до назначения локальной переменной. (Сообщение об ошибке: “UnboundLocalError: local variable 'foobar' referenced before assignment”)
Использовать локальную переменную в функции, имя которой совпадает с именем глобальной переменной, довольно сложно. Правило таково: если переменной в функции когда-либо назначается что-то, она всегда является локальной переменной, когда используется внутри этой функции. В противном случае, это глобальная переменная внутри этой функции.
Это означает, что вы не можете использовать ее как глобальную переменную в функции до ее назначения.
Пример кода с ошибкой:
someVar = 42
def myFunction():
print(someVar)
someVar = 100
myFunction()
15) Попытка использовать range() для создания списка целых чисел. (Сообщение об ошибке: “TypeError: 'range' object does not support item assignment”)
Иногда вам нужен список целочисленных значений по порядку, поэтому range() кажется хорошим способом создать этот список. Однако вы должны помнить, что range() возвращает «объект диапазона», а не фактическое значение списка.
Пример кода с ошибкой:
spam = range(10)
spam[4] = -1
То что вы хотите сделать, выглядит так:
spam = list(range(10))
spam[4] = -1
(UPD: Это работает в Python 2, потому что Python 2’s range() возвращает список значений. Но, попробовав сделать это в Python 3, вы увидите ошибку.)
16) Нет оператора ++ инкремента или -- декремента. (Сообщение об ошибке: “SyntaxError: invalid syntax”)
Если вы пришли из другого языка программирования, такого как C++, Java или PHP, вы можете попытаться увеличить или уменьшить переменную с помощью ++ или --. В Python таких операторов нет.
Пример кода с ошибкой:
spam = 0
spam++
То что вы хотите сделать, выглядит так:
spam = 0
spam += 1
17) UPD: как указывает Luchano в комментариях, также часто забывают добавить self в качестве первого параметра для метода. (Сообщение об ошибке: «TypeError: TypeError: myMethod() takes no arguments (1 given)»)
Пример кода с ошибкой:
class Foo():
def myMethod():
print('Hello!')
a = Foo()
a.myMethod()
Краткое объяснение различных сообщений об ошибках приведено в Приложении D книги «Invent with Python».

Узнайте подробности, как получить востребованную профессию с нуля или Level Up по навыкам и зарплате, пройдя онлайн-курсы SkillFactory:
- Курс «Профессия Data Scientist» (24 месяца)
- Курс «Профессия Data Analyst» (18 месяцев)
- Курс «Python для веб-разработки» (9 месяцев)
Читать еще
- 450 бесплатных курсов от Лиги Плюща
- Бесплатные курсы по Data Science от Harvard University
- 30 лайфхаков чтобы пройти онлайн-курс до конца
- Самый успешный и самый скандальный Data Science проект: Cambridge Analytica