File stdin line 1 in module python ошибка

  1. the file "<stdin>", line 1, in <module> Error in Python
  2. Resolve the File "<stdin>", line 1, in <module> Error in Python
  3. Conclusion

File <Stdin>, Line 1, in <Module> Error in Python

Errors are something that we often encounter while coding in any particular programming language. However, there are mainly three types of errors: syntax, logical, and runtime.

In this article, we will be discussing the most common syntax error that people face, which is the File "<stdin>", line 1, in <module> error. Let us see why this error occurs and how to resolve it in Python.

the file "<stdin>", line 1, in <module> Error in Python

Errors are unexpected situations that the programmers commit that result in the unusual working of the program. As discussed earlier, there are mainly three types of errors: Syntax, Logical, and Runtime.

However, we will mainly be concerned about a particular syntax error File "<stdin>", line 1, in <module> in this article that beginners or even experienced professionals often encounter while programming in Python.

Syntax errors occur when there is a problem in the program’s syntax. For example, using a keyword as a variable, incorrect indentation of the code, etc.

Therefore, this error mainly occurs if we use invalid syntax in our program.

The error File "<stdin>", line 1, in <module> is also a type of syntax error that occurs whenever we have a problem with the syntax of the program while using the Python interpreter.

The error refers to a problem in line 1 of the program followed by an error message that signifies the error in the program. Moreover, it also displays a line number to indicate where to look in the code for the mentioned error.

Now, let us see some examples of the error File "<stdin>", line 1, in <module>.

Resolve the File "<stdin>", line 1, in <module> Error in Python

Now, we will be seeing some of the examples of the File "<stdin>", line 1, in <module> error and how this error can be resolved in Python.

Running a Python File on the Interpreter Gives the File "<stdin>", line 1, in <module> Error

When we try to run a Python file in the Python interpreter, we encounter this error below.

Below is the Python file ex1.py to be executed.

print("Hello, user!")
print("Welcome to the page,")
print("Hope you will enjoy the experience.")

However, when we try to run this ex1.py file in the interpreter, we get the following output.

>>> python ex1.py
  File "<stdin>", line 1
    python ex1.py
           ^
SyntaxError: invalid syntax

However, it occurs because the file ex1.py should not be executed on the Python interpreter but should have been done on the terminal.

Python interpreters are meant to run only valid Python statements and not the whole files. Therefore, we should use the terminal for that whenever we have to run a Python file.

However, to get back to the terminal while you are using the Python interpreter, you should either type exit() and press the Enter key to take an exit from the Python interpreter or directly press CTRL+D for exiting the Python interpreter.

Let us see how to take an exit from the Python interpreter.

Now, you must have been at the terminal. Therefore, go to the specified path on which your Python file is saved and then write python <file_name> to run your file without getting the File "<stdin>", line 1, in <module> error.

The output will appear something like below on executing the desired file.

D:poll>python ex1.py
Hello, user!
Welcome to the page,
Hope you will enjoy the experience.

In this way, we can remove the File "<stdin>", line 1, in <module> error from our program.

Invalid Syntax Statements in Python Causes the File "<stdin>", line 1, in <module> Error

The invalid syntax, such as using invalid names, division of a number by 0, etc., can also cause the File "<stdin>", line 1, in <module> error. Let us now see them in detail.

Output:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined

Therefore, the output shows the File "<stdin>", line 1, in <module> NameError error as the answer variable is assigned a value of x which is not defined anywhere in the program.

To resolve the issue, we need to define the variable x below the answer variable.

However, another example of the File "<stdin>", line 1, in <module> error can be the division of a number by 0. Let us have a look at it.

>>> 1/0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero

Therefore, as you can see above, the division throws the same error.

However, all the above examples are executed on the interpreter, and they work fine because they are single statements and not files. Therefore, you must remember that you can only execute valid statements on the Python interpreter, not the whole Python file.

For executing the Python files, you must use the terminal.

Moreover, the error File "<stdin>", line 1, in <module> can also be written as File "<stdin>", line 6, in <module> depending on the line number on which the error is encountered but the meaning of the error and the way to solve it remains the same.

Conclusion

In this article, we have studied the most common error that programmers often encounter while programming in Python, which is the File "<stdin>", line 1, in <module> error. This error often occurs because of executing a file in the Python interpreter or having some syntax errors in the Python code.

However, we have discussed how these errors can be resolved that are executing a Python file in a terminal instead of the interpreter in the case of a file, whereas resolving the appropriate syntax errors in the program in the case of the Python statements.

It seems that there is confusion about how Python code can be executed and processed.

  1. On the one hand, there is the Python interpreter in the interactive mode. This is usually started with the command python (without arguments) and then you have the possibility to execute Python code directly in an interactive Python specific shell. This distinguishes Python from other languages that need to be compiled first to execute code. Further information are available in the official Python tutorial.
  2. On the other hand, Python can also be executed in such a way that not the interpreter with an interactive shell is started, but a file is read and processed. This is usually done with the command python together with the path to the Python file as argument, e.g. python test.py. See also the documentation about using Python.

With this knowledge the problems that have happened to you can now be explained and solved:

If you are simply starting the Python interpreter in interactive mode (without any further arguments), you don’t have access to the command line arguments any more, for example:

$ python3.8  # or whatever your command is, maybe only python or python3
Python 3.8.0 (default, Oct 28 2019, 16:14:01) 
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys; sys.argv
['']

As you can see, there isn’t really a usable information in argv. And that is your problem: The arguments aren’t successfully loaded into sys.argv. So an index error happened, because the arguments are simply missing:

$ python3.8
Python 3.8.0 (default, Oct 28 2019, 16:14:01) 
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.argv[1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

The only difference to your example is that you have already provided the path to the script, because it’s File "C:/Users/MJavad/Desktop/test.py", line 3, in <module> instead of File "<stdin>", line 1, in <module>. So you have started the program via python test.py, but also without any further arguments which would be loaded into sys.argv in the program, see:

$ python3.8 test.py
Traceback (most recent call last):
  File "test.py", line 3, in <module>
    b = float(sys.argv[1])
IndexError: list index out of range

Your sys.argv now looks like this: ['test.py'], but still no index positions 1 and 2 available. So you have to invoke python also with additional arguments which will be passed into sys.argv:

$ python3.8 test.py 1 2
Traceback (most recent call last):
  File "test.py", line 6, in <module>
    d = math.sqrt(f)
ValueError: math domain error

And it worked! Ok, you have another exception, but it’s in line 6 and every line before was successfully processed, also the command line arguments. Now you can proceed to debug your program, i.e. start programming or trying other parameters than 1 and 2 etc.

So that’s the theory. Since you’re also using PyCharm and have the «Terminal», the «Run configuration» and a «Python Console» available, things get a bit more complicated:

  1. The «Terminal» should have a prompt available if you start one. This prompt shouldn’t be a prompt from the Python interpreter (normally prefixed by >>>). It should be a terminal prompt (normally prefixed by an $ at the end), where you can also start a python interpreter in interactive mode or start a python program as described above. This «Terminal» is a terminal emulator given you by PyCharm and can also do other things for you, not only starting python programs. See the PyCharm documentation for more information.
  2. The «Python Console» is a similar Python interpreter you also can get if starting python from the «Terminal». But then, you already started the interactive mode of the interpreter and there are no possibilities to pass command line arguments (maybe somewhere, but not as default). See the PyCharm documentation for more information.
  3. If you’re using an IDE like PyCharm, you should normally start the program as recommended by the IDE. In this case, you’re writing a file and start the file neither by running the «Terminal», nor going into an interactive Python shell. Instead of this, you have to configure the IDE «Run» as described in the PyCharm documentation or as you can see here:

    run configuration

    This is just the GUI way of calling python C:/Users/MJavad/Desktop/test.py 1 2 directly inside PyCharm.

So I would recommend that you’re only starting your programs via option 3 (via «Run» configuration or «DEBUG» configuration). You only have to pay attention, running the right configuration (see if the path is the correct one and the parameters are right).

It is not normal to have a Python prompt (>>>) directly after starting a «Terminal», though. And inside interactive mode of Python’s interpreter, you simply cannot start a python script, because you’re already in a python interpreter, for example:

$ python3.8
Python 3.8.0 (default, Oct 28 2019, 16:14:01) 
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> python test.py 1 2
  File "<stdin>", line 1
    python test.py 1 2
           ^
SyntaxError: invalid syntax

I should also mention that you can pass arguments into python interactive mode, for example (the - stands for <stdin>):

$ python3.8 - hello world
Python 3.8.0 (default, Oct 28 2019, 16:14:01) 
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys; sys.argv
['-', 'hello', 'world']
>>> 

Python выводит трассировку (далее traceback), когда в вашем коде появляется ошибка. Вывод traceback может быть немного пугающим, если вы видите его впервые, или не понимаете, чего от вас хотят. Однако traceback Python содержит много информации, которая может помочь вам определить и исправить причину, из-за которой в вашем коде возникла ошибка.

Содержание статьи

  • Traceback — Что это такое и почему оно появляется?
  • Как правильно читать трассировку?
  • Обзор трассировка Python
  • Подробный обзор трассировки в Python
  • Обзор основных Traceback исключений в Python
  • AttributeError
  • ImportError
  • IndexError
  • KeyError
  • NameError
  • SyntaxError
  • TypeError
  • ValueError
  • Логирование ошибок из Traceback
  • Вывод

Понимание того, какую информацию предоставляет traceback Python является основополагающим критерием того, как стать лучшим Python программистом.

К концу данной статьи вы сможете:

  • Понимать, что несет за собой traceback
  • Различать основные виды traceback
  • Успешно вести журнал traceback, при этом исправить ошибку

Python Traceback — Как правильно читать трассировку?

Traceback (трассировка) — это отчет, который содержит вызовы выполненных функций в вашем коде в определенный момент.

Есть вопросы по Python?

На нашем форуме вы можете задать любой вопрос и получить ответ от всего нашего сообщества!

Telegram Чат & Канал

Вступите в наш дружный чат по Python и начните общение с единомышленниками! Станьте частью большого сообщества!

Паблик VK

Одно из самых больших сообществ по Python в социальной сети ВК. Видео уроки и книги для вас!

Traceback называют по разному, иногда они упоминаются как трассировка стэка, обратная трассировка, и так далее. В Python используется определение “трассировка”.

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

def say_hello(man):

    print(‘Привет, ‘ + wrong_variable)

say_hello(‘Иван’)

Здесь say_hello() вызывается с параметром man. Однако, в say_hello() это имя переменной не используется. Это связано с тем, что оно написано по другому: wrong_variable в вызове print().

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

Когда вы запускаете эту программу, вы получите следующую трассировку:

Traceback (most recent call last):

  File «/home/test.py», line 4, in <module>

    say_hello(‘Иван’)

  File «/home/test.py», line 2, in say_hello

    print(‘Привет, ‘ + wrong_variable)

NameError: name ‘wrong_variable’ is not defined

Process finished with exit code 1

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

В traceback выше, ошибкой является NameError, она означает, что есть отсылка к какому-то имени (переменной, функции, класса), которое не было определено. В данном случае, ссылаются на имя wrong_variable.

Последняя строка содержит достаточно информации для того, чтобы вы могли решить эту проблему. Поиск переменной wrong_variable, и заменит её атрибутом из функции на man. Однако, скорее всего в реальном случае вы будете иметь дело с более сложным кодом.

Python Traceback — Как правильно понять в чем ошибка?

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

Существует несколько секций для каждой трассировки Python, которые являются крайне важными. Диаграмма ниже описывает несколько частей:

Обзор трассировки Python

В Python лучше всего читать трассировку снизу вверх.

  1. Синее поле: последняя строка из traceback — это строка уведомления об ошибке. Синий фрагмент содержит название возникшей ошибки.
  2. Зеленое поле: после названия ошибки идет описание ошибки. Это описание обычно содержит полезную информацию для понимания причины возникновения ошибки.
  3. Желтое поле: чуть выше в трассировке содержатся различные вызовы функций. Снизу вверх — от самых последних, до самых первых. Эти вызовы представлены двухстрочными вводами для каждого вызова. Первая строка каждого вызова содержит такую информацию, как название файла, номер строки и название модуля. Все они указывают на то, где может быть найден код.
  4. Красное подчеркивание: вторая строка этих вызовов содержит непосредственный код, который был выполнен с ошибкой.

Есть ряд отличий между выдачей трассировок, когда вы запускает код в командной строке, и между запуском кода в REPL. Ниже вы можете видеть тот же код из предыдущего раздела, запущенного в REPL и итоговой выдачей трассировки:

Python 3.7.4 (default, Jul 16 2019, 07:12:58)

[GCC 9.1.0] on linux

Type «help», «copyright», «credits» or «license» for more information.

>>>

>>>

>>> def say_hello(man):

...     print(‘Привет, ‘ + wrong_variable)

...

>>> say_hello(‘Иван’)

Traceback (most recent call last):

  File «<stdin>», line 1, in <module>

  File «<stdin>», line 2, in say_hello

NameError: name ‘wrong_variable’ is not defined

Обратите внимание на то, что на месте названия файла вы увидите <stdin>. Это логично, так как вы выполнили код через стандартный ввод. Кроме этого, выполненные строки кода не отображаются в traceback.

Важно помнить: если вы привыкли видеть трассировки стэка в других языках программирования, то вы обратите внимание на явное различие с тем, как выглядит traceback в Python. Большая часть других языков программирования выводят ошибку в начале, и затем ведут сверху вниз, от недавних к последним вызовам.

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

Traceback в Python на примерах кода

Изучение отдельно взятой трассировки поможет вам лучше понять и увидеть, какая информация в ней вам дана и как её применить.

Код ниже используется в примерах для иллюстрации информации, данной в трассировке Python:

Мы запустили ниже предоставленный код в качестве примера и покажем какую информацию мы получили от трассировки.

Сохраняем данный код в файле greetings.py

def who_to_greet(person):

    return person if person else input(‘Кого приветствовать? ‘)

def greet(someone, greeting=‘Здравствуйте’):

    print(greeting + ‘, ‘ + who_to_greet(someone))

def greet_many(people):

    for person in people:

        try:

            greet(person)

        except Exception:

            print(‘Привет, ‘ + person)

Функция who_to_greet() принимает значение person и либо возвращает данное значение если оно не пустое, либо запрашивает  значение от пользовательского ввода через input().

Далее, greet() берет имя для приветствия из someone, необязательное значение из greeting и вызывает print(). Также с переданным значением из someone вызывается who_to_greet().

Наконец, greet_many() выполнит итерацию по списку людей и вызовет greet(). Если при вызове greet() возникает ошибка, то выводится резервное приветствие print('hi, ' + person).

Этот код написан правильно, так что никаких ошибок быть не может при наличии правильного ввода.

Если вы добавите вызов функции greet() в конце нашего кода (которого сохранили в файл greetings.py) и дадите аргумент который он не ожидает (например, greet('Chad', greting='Хай')), то вы получите следующую трассировку:

$ python greetings.py

Traceback (most recent call last):

  File «/home/greetings.py», line 19, in <module>

    greet(‘Chad’, greting=‘Yo’)

TypeError: greet() got an unexpected keyword argument ‘greting’

Еще раз, в случае с трассировкой Python, лучше анализировать снизу вверх. Начиная с последней строки трассировки, вы увидите, что ошибкой является TypeError. Сообщения, которые следуют за типом ошибки, дают вам полезную информацию. Трассировка сообщает, что greet() вызван с аргументом, который не ожидался. Неизвестное название аргумента предоставляется в том числе, в нашем случае это greting.

Поднимаясь выше, вы можете видеть строку, которая привела к исключению. В данном случае, это вызов greet(), который мы добавили в конце greetings.py.

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

С другим файлом и другим вводом, вы можете увидеть, что трассировка явно указывает вам на правильное направление, чтобы найти проблему. Следуя этой информации, мы удаляем злополучный вызов greet() в конце greetings.py, и добавляем следующий файл под названием example.py в папку:

from greetings import greet

greet(1)

Здесь вы настраиваете еще один файл Python, который импортирует ваш предыдущий модуль greetings.py, и используете его greet(). Вот что произойдете, если вы запустите example.py:

$ python example.py

Traceback (most recent call last):

  File «/path/to/example.py», line 3, in <module>

    greet(1)

  File «/path/to/greetings.py», line 5, in greet

    print(greeting + ‘, ‘ + who_to_greet(someone))

TypeError: must be str, not int

В данном случае снова возникает ошибка TypeError, но на этот раз уведомление об ошибки не очень помогает. Оно говорит о том, что где-то в коде ожидается работа со строкой, но было дано целое число.

Идя выше, вы увидите строку кода, которая выполняется. Затем файл и номер строки кода. На этот раз мы получаем имя функции, которая была выполнена — greet().

Поднимаясь к следующей выполняемой строке кода, мы видим наш проблемный вызов greet(), передающий целое число.

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

Так как это может сбивать с толку, рассмотрим пример. Добавим вызов greet_many() в конце greetings.py:

# greetings.py

...

greet_many([‘Chad’, ‘Dan’, 1])

Это должно привести к выводу приветствия всем трем людям. Однако, если вы запустите этот код, вы увидите несколько трассировок в выдаче:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

$ python greetings.py

Hello, Chad

Hello, Dan

Traceback (most recent call last):

  File «greetings.py», line 10, in greet_many

    greet(person)

  File «greetings.py», line 5, in greet

    print(greeting + ‘, ‘ + who_to_greet(someone))

TypeError: must be str, not int

During handling of the above exception, another exception occurred:

Traceback (most recent call last):

  File «greetings.py», line 14, in <module>

    greet_many([‘Chad’, ‘Dan’, 1])

  File «greetings.py», line 12, in greet_many

    print(‘hi, ‘ + person)

TypeError: must be str, not int

Обратите внимание на выделенную строку, начинающуюся с “During handling in the output above”. Между всеми трассировками, вы ее увидите.

Это достаточно ясное уведомление: Пока ваш код пытался обработать предыдущую ошибку, возникла новая.

Обратите внимание: функция отображения предыдущих трассировок была добавлена в Python 3. В Python 2 вы можете получать только трассировку последней ошибки.

Вы могли видеть предыдущую ошибку, когда вызывали greet() с целым числом. Так как мы добавили 1 в список людей для приветствия, мы можем ожидать тот же результат. Однако, функция greet_many() оборачивает вызов greet() и пытается в блоке try и except. На случай, если greet() приведет к ошибке, greet_many() захочет вывести приветствие по-умолчанию.

Соответствующая часть greetings.py повторяется здесь:

def greet_many(people):

    for person in people:

        try:

            greet(person)

        except Exception:

            print(‘hi, ‘ + person)

Когда greet() приводит к TypeError из-за неправильного ввода числа, greet_many() обрабатывает эту ошибку и пытается вывести простое приветствие. Здесь код приводит к другой, аналогичной ошибке. Он все еще пытается добавить строку и целое число.

Просмотр всей трассировки может помочь вам увидеть, что стало причиной ошибки. Иногда, когда вы получаете последнюю ошибку с последующей трассировкой, вы можете не увидеть, что пошло не так. В этих случаях, изучение предыдущих ошибок даст лучшее представление о корне проблемы.

Обзор основных Traceback исключений в Python 3

Понимание того, как читаются трассировки Python, когда ваша программа выдает ошибку, может быть очень полезным навыком, однако умение различать отдельные трассировки может заметно ускорить вашу работу.

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

Ошибка AttributeError object has no attribute [Решено]

AttributeError возникает тогда, когда вы пытаетесь получить доступ к атрибуту объекта, который не содержит определенного атрибута. Документация Python определяет, когда эта ошибка возникнет:

Возникает при вызове несуществующего атрибута или присвоение значения несуществующему атрибуту.

Пример ошибки AttributeError:

>>> an_int = 1

>>> an_int.an_attribute

Traceback (most recent call last):

  File «<stdin>», line 1, in <module>

AttributeError: ‘int’ object has no attribute ‘an_attribute’

Строка уведомления об ошибке для AttributeError говорит вам, что определенный тип объекта, в данном случае int, не имеет доступа к атрибуту, в нашем случае an_attribute. Увидев AttributeError в строке уведомления об ошибке, вы можете быстро определить, к какому атрибуту вы пытались получить доступ, и куда перейти, чтобы это исправить.

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

>>> a_list = (1, 2)

>>> a_list.append(3)

Traceback (most recent call last):

  File «<stdin>», line 1, in <module>

AttributeError: ‘tuple’ object has no attribute ‘append’

В примере выше, вы можете ожидать, что a_list будет типом списка, который содержит метод .append(). Когда вы получаете ошибку AttributeError, и видите, что она возникла при попытке вызова .append(), это говорит о том, что вы, возможно, не работаете с типом объекта, который ожидаете.

Часто это происходит тогда, когда вы ожидаете, что объект вернется из вызова функции или метода и будет принадлежать к определенному типу, но вы получаете тип объекта None. В данном случае, строка уведомления об ошибке будет выглядеть так:

AttributeError: ‘NoneType’ object has no attribute ‘append’

Python Ошибка ImportError: No module named [Решено]

ImportError возникает, когда что-то идет не так с оператором import. Вы получите эту ошибку, или ее подкласс ModuleNotFoundError, если модуль, который вы хотите импортировать, не может быть найден, или если вы пытаетесь импортировать что-то, чего не существует во взятом модуле. Документация Python определяет, когда возникает эта ошибка:

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

Вот пример появления ImportError и ModuleNotFoundError:

>>> import asdf

Traceback (most recent call last):

  File «<stdin>», line 1, in <module>

ModuleNotFoundError: No module named ‘asdf’

>>> from collections import asdf

Traceback (most recent call last):

  File «<stdin>», line 1, in <module>

ImportError: cannot import name ‘asdf’

В примере выше, вы можете видеть, что попытка импорта модуля asdf, который не существует, приводит к ModuleNotFoundError. При попытке импорта того, что не существует (в нашем случае — asdf) из модуля, который существует (в нашем случае — collections), приводит к ImportError. Строки сообщения об ошибке трассировок указывают на то, какая вещь не может быть импортирована, в обоих случаях это asdf.

Ошибка IndexError: list index out of range [Решено]

IndexError возникает тогда, когда вы пытаетесь вернуть индекс из последовательности, такой как список или кортеж, и при этом индекс не может быть найден в последовательности. Документация Python определяет, где эта ошибка появляется:

Возникает, когда индекс последовательности находится вне диапазона.

Вот пример, который приводит к IndexError:

>>> a_list = [‘a’, ‘b’]

>>> a_list[3]

Traceback (most recent call last):

  File «<stdin>», line 1, in <module>

IndexError: list index out of range

Строка сообщения об ошибке для IndexError не дает вам полную информацию. Вы можете видеть, что у вас есть отсылка к последовательности, которая не доступна и то, какой тип последовательности рассматривается, в данном случае это список.

Иными словами, в списке a_list нет значения с ключом 3. Есть только значение с ключами 0 и 1, это a и b соответственно.

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

Возникает ошибка KeyError в Python 3 [Решено]

Как и в случае с IndexError, KeyError возникает, когда вы пытаетесь получить доступ к ключу, который отсутствует в отображении, как правило, это dict. Вы можете рассматривать его как IndexError, но для словарей. Из документации:

Возникает, когда ключ словаря не найден в наборе существующих ключей.

Вот пример появления ошибки KeyError:

>>> a_dict = [‘a’: 1, ‘w’: ‘2’]

>>> a_dict[‘b’]

Traceback (most recent call last):

  File «<stdin>», line 1, in <module>

KeyError: ‘b’

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

Ошибка NameError: name is not defined в Python [Решено]

NameError возникает, когда вы ссылаетесь на название переменной, модуля, класса, функции, и прочего, которое не определено в вашем коде.

Документация Python дает понять, когда возникает эта ошибка NameError:

Возникает, когда локальное или глобальное название не было найдено.

В коде ниже, greet() берет параметр person. Но в самой функции, этот параметр был назван с ошибкой, persn:

>>> def greet(person):

...     print(f‘Hello, {persn}’)

>>> greet(‘World’)

Traceback (most recent call last):

  File «<stdin>», line 1, in <module>

  File «<stdin>», line 2, in greet

NameError: name ‘persn’ is not defined

Строка уведомления об ошибке трассировки NameError указывает вам на название, которое мы ищем. В примере выше, это названная с ошибкой переменная или параметр функции, которые были ей переданы.

NameError также возникнет, если берется параметр, который мы назвали неправильно:

>>> def greet(persn):

...     print(f‘Hello, {person}’)

>>> greet(‘World’)

Traceback (most recent call last):

  File «<stdin>», line 1, in <module>

  File «<stdin>», line 2, in greet

NameError: name ‘person’ is not defined

Здесь все выглядит так, будто вы сделали все правильно. Последняя строка, которая была выполнена, и на которую ссылается трассировка выглядит хорошо.

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

Ошибка SyntaxError: invalid syntax в Python [Решено]

Возникает, когда синтаксический анализатор обнаруживает синтаксическую ошибку.

Ниже, проблема заключается в отсутствии двоеточия, которое должно находиться в конце строки определения функции. В REPL Python, эта ошибка синтаксиса возникает сразу после нажатия Enter:

>>> def greet(person)

  File «<stdin>», line 1

    def greet(person)

                    ^

SyntaxError: invalid syntax

Строка уведомления об ошибке SyntaxError говорит вам только, что есть проблема с синтаксисом вашего кода. Просмотр строк выше укажет вам на строку с проблемой. Каретка ^ обычно указывает на проблемное место. В нашем случае, это отсутствие двоеточия в операторе def нашей функции.

Стоит отметить, что в случае с трассировками SyntaxError, привычная первая строка Tracebak (самый последний вызов) отсутствует. Это происходит из-за того, что SyntaxError возникает, когда Python пытается парсить ваш код, но строки фактически не выполняются.

Ошибка TypeError в Python 3 [Решено]

TypeError возникает, когда ваш код пытается сделать что-либо с объектом, который не может этого выполнить, например, попытка добавить строку в целое число, или вызвать len() для объекта, в котором не определена длина.

Ошибка возникает, когда операция или функция применяется к объекту неподходящего типа.

Рассмотрим несколько примеров того, когда возникает TypeError:

>>> 1 + ‘1’

Traceback (most recent call last):

  File «<stdin>», line 1, in <module>

TypeError: unsupported operand type(s) for +: ‘int’ and ‘str’

>>> ‘1’ + 1

Traceback (most recent call last):

  File «<stdin>», line 1, in <module>

TypeError: must be str, not int

>>> len(1)

Traceback (most recent call last):

  File «<stdin>», line 1, in <module>

TypeError: object of type ‘int’ has no len()

Указанные выше примеры возникновения TypeError приводят к строке уведомления об ошибке с разными сообщениями. Каждое из них весьма точно информирует вас о том, что пошло не так.

В первых двух примерах мы пытаемся внести строки и целые числа вместе. Однако, они немного отличаются:

  • В первом примере мы пытаемся добавить str к int.
  • Во втором примере мы пытаемся добавить int к str.

Уведомления об ошибке указывают на эти различия.

Последний пример пытается вызвать len() для int. Сообщение об ошибке говорит нам, что мы не можем сделать это с int.

Возникла ошибка ValueError в Python 3 [Решено]

ValueError возникает тогда, когда значение объекта не является корректным. Мы можем рассматривать это как IndexError, которая возникает из-за того, что значение индекса находится вне рамок последовательности, только ValueError является более обобщенным случаем.

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

Вот два примера возникновения ошибки ValueError:

>>> a, b, c = [1, 2]

Traceback (most recent call last):

  File «<stdin>», line 1, in <module>

ValueError: not enough values to unpack (expected 3, got 2)

>>> a, b = [1, 2, 3]

Traceback (most recent call last):

  File «<stdin>», line 1, in <module>

ValueError: too many values to unpack (expected 2)

Строка уведомления об ошибке ValueError в данных примерах говорит нам в точности, в чем заключается проблема со значениями:

  1. В первом примере, мы пытаемся распаковать слишком много значений. Строка уведомления об ошибке даже говорит нам, где именно ожидается распаковка трех значений, но получаются только два.
  2. Во втором примере, проблема в том, что мы получаем слишком много значений, при этом получаем недостаточно значений для распаковки.

Логирование ошибок из Traceback в Python 3

Получение ошибки, и ее итоговой трассировки указывает на то, что вам нужно предпринять для решения проблемы. Обычно, отладка кода — это первый шаг, но иногда проблема заключается в неожиданном, или некорректном вводе. Хотя важно предусматривать такие ситуации, иногда есть смысл скрывать или игнорировать ошибку путем логирования traceback.

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

Файл urlcaller.py:

import sys

import requests

response = requests.get(sys.argv[1])

print(response.status_code, response.content)

Этот код работает исправно. Когда вы запускаете этот скрипт, задавая ему URL в качестве аргумента командной строки, он откроет данный URL, и затем выведет HTTP статус кода и содержимое страницы (content) из response. Это работает даже в случае, если ответом является статус ошибки HTTP:

$ python urlcaller.py https://httpbin.org/status/200

200 b»

$ python urlcaller.py https://httpbin.org/status/500

500 b»

Однако, иногда данный URL не существует (ошибка 404 — страница не найдена), или сервер не работает. В таких случаях, этот скрипт приводит к ошибке ConnectionError и выводит трассировку:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

$ python urlcaller.py http://thisurlprobablydoesntexist.com

...

During handling of the above exception, another exception occurred:

Traceback (most recent call last):

  File «urlcaller.py», line 5, in <module>

    response = requests.get(sys.argv[1])

  File «/path/to/requests/api.py», line 75, in get

    return request(‘get’, url, params=params, **kwargs)

  File «/path/to/requests/api.py», line 60, in request

    return session.request(method=method, url=url, **kwargs)

  File «/path/to/requests/sessions.py», line 533, in request

    resp = self.send(prep, **send_kwargs)

  File «/path/to/requests/sessions.py», line 646, in send

    r = adapter.send(request, **kwargs)

  File «/path/to/requests/adapters.py», line 516, in send

    raise ConnectionError(e, request=request)

requests.exceptions.ConnectionError: HTTPConnectionPool(host=‘thisurlprobablydoesntexist.com’, port=80): Max retries exceeded with url: / (Caused by NewConnectionError(‘<urllib3.connection.HTTPConnection object at 0x7faf9d671860>: Failed to establish a new connection: [Errno -2] Name or service not known’,))

Трассировка Python в данном случае может быть очень длинной, и включать в себя множество других ошибок, которые в итоге приводят к ошибке ConnectionError. Если вы перейдете к трассировке последних ошибок, вы заметите, что все проблемы в коде начались на пятой строке файла urlcaller.py.

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

Файл urlcaller.py:

try:

    response = requests.get(sys.argv[1])

except requests.exceptions.ConnectionError:

    print(1, ‘Connection Error’)

else:

    print(response.status_code, response.content)

Код выше использует предложение else с блоком except.

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

$ python urlcaller.py http://thisurlprobablydoesntexist.com

1 Connection Error

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

Обратите внимание: Для более лучшего представления о системе логирования в Python вы можете ознакомиться с данным руководством тут: Логирование в Python

Вы можете вести журнал трассировки в скрипте, импортировав пакет logging, получить logger, вызвать .exception() для этого логгера в куске except блока try и except. Конечный скрипт будет выглядеть примерно так:

# urlcaller.py

import logging

import sys

import requests

logger = logging.getLogger(__name__)

try:

    response = requests.get(sys.argv[1])

except requests.exceptions.ConnectionError as e:

    logger.exception()

    print(1, ‘Connection Error’)

else:

    print(response.status_code, response.content)

Теперь, когда вы запускаете скрипт с проблемным URL, он будет выводить исключенные -1 и ConnectionError, но также будет вести журнал трассировки:

$ python urlcaller.py http://thisurlprobablydoesntexist.com

...

  File «/path/to/requests/adapters.py», line 516, in send

    raise ConnectionError(e, request=request)

requests.exceptions.ConnectionError: HTTPConnectionPool(host=‘thisurlprobablydoesntexist.com’, port=80): Max retries exceeded with url: / (Caused by NewConnectionError(‘<urllib3.connection.HTTPConnection object at 0x7faf9d671860>: Failed to establish a new connection: [Errno -2] Name or service not known’,))

1 Connection Error

По умолчанию, Python будет выводить ошибки в стандартный stderr. Выглядит так, будто мы совсем не подавили вывод трассировки. Однако, если вы выполните еще один вызов при перенаправлении stderr, вы увидите, что система ведения журналов работает, и мы можем изучать логи программы без необходимости личного присутствия во время появления ошибок:

$ python urlcaller.py http://thisurlprobablydoesntexist.com 2> mylogs.log

1 Connection Error

Подведем итоги данного обучающего материала

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

Понимание содержимого трассировки Python, когда вы запускаете ваш код может быть ключом к улучшению вашего кода. Это способ, которым Python пытается вам помочь.

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

  • Текст является переводом статьи: Understanding the Python Traceback
  • Изображение из шапки статьи принадлежит сайту © Real Python

Являюсь администратором нескольких порталов по обучению языков программирования Python, Golang и Kotlin. В составе небольшой команды единомышленников, мы занимаемся популяризацией языков программирования на русскоязычную аудиторию. Большая часть статей была адаптирована нами на русский язык и распространяется бесплатно.

E-mail: vasile.buldumac@ati.utm.md

Образование
Universitatea Tehnică a Moldovei (utm.md)

  • 2014 — 2018 Технический Университет Молдовы, ИТ-Инженер. Тема дипломной работы «Автоматизация покупки и продажи криптовалюты используя технический анализ»
  • 2018 — 2020 Технический Университет Молдовы, Магистр, Магистерская диссертация «Идентификация человека в киберпространстве по фотографии лица»

Содержание

  • Заголовок
    • Чтение Traceback 1
    • Чтение Traceback 2
  • Некоторые ошибки с примерами кода
    • Ошибки в синтаксисе
    • Ошибки в логике
  • Контест №1

Заголовок

Создайте файл solution.py со следующим кодом:

for coord in vector:
    print(coord)

Наш код подразумевает печать содержимого переменной vector.

Запустим написанный скрипт, получим следующий вывод:

$ python3 solution.py
Traceback (most recent call last):
  File "solution.py", line 1, in <module>
    for coord in vector:
NameError: name 'vector' is not defined

Сообщение означает, что при исполнении кода возникла ошибка.
При этом Python сообщает нам кое-что ещё.
Разберём это сообщение детально.

Чтение Traceback 1

Исходное сообщение нужно мысленно разделить на две части.
Первая часть это traceback-сообщение:

Traceback (most recent call last):
  File "solution.py", line 1, in <module>
    for coord in vector:

Вторая часть — сообщение о возникшей ошибке:

NameError: name 'vector' is not defined

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

Первая строка:

Traceback (most recent call last):

является заголовочной.
Она сообщает, что в последующих строках будет изложен стэк вызовов (он показан отступами).
Обратите внимание на сообщение в скобках, оно указывает на порядок вызовов.
В данном случае (он же случай по умолчанию) тот вызов, в котором произошла ошибка, будет в последовательности вызовов указан последним.

Вторая и третья строки:

File "solution.py", line 1, in <module>
  for coord in vector:

показывают информацию о вызове (в нашем случае он один).
Во-первых, здесь есть информация о файле, в котором произошёл вызов («solution.py»), затем указан номер строки, где этот вызов происходит («line 1»), в конце стоит информация о том, откуда произошёл вызов («<module>»).
В нашем случае вызов происходит непосредственно из модуля, т.е. не из функции.
Наконец, вывод содержит не только номер строки, но и саму строку «for coord in vector:».

Заключительная строка сообщения:

NameError: name 'vector' is not defined

содержит вид (тип) ошибки («NameError»), и после двоеточия содержит подсказку.
В данном случае она означает, что имя «vector» не определено.

В самом деле, если взглянуть снова на код, то можно убедиться, что мы нигде не объявили переменную «vector».

Подведём итоги.
При попытке запуска мы получили следующий вывод

$ python3 solution.py
Traceback (most recent call last):
  File "solution.py", line 1, in <module>
    for coord in vector:
NameError: name 'vector' is not defined

Он говорит нам о возникновении ошибки.
Эта ошибка обнаружилась интерпретатором в первой строке файла «solution.py».
Сама ошибка является ошибкой имени и указывает на необъявленное имя — «vector».

Чтение Traceback 2

Оберните код из solution.py в функцию:

def print_vector(vector):
    for coord in vector:
        print(coord)

print_vector(5)

Запустим наш код

$ python3 solution.py
Traceback (most recent call last):
  File "solution.py", line 5, in <module>
    print_vector(5)
  File "solution.py", line 2, in print_vector
    for coord in vector:
TypeError: 'int' object is not iterable

На этот раз сообщение об ошибке сложнее, однако структура у него та же.

Часть со стеком вызовов увеличилась:

Traceback (most recent call last):
  File "solution.py", line 5, in <module>
    print_vector(5)
  File "solution.py", line 2, in print_vector
    for coord in vector:

Поскольку «most recent call last», читать будем её сверху вниз.

Вызовов на этот раз два.
Первый вызов:

File "solution.py", line 5, in <module>
  print_vector(5)

Произошел в пятой строке.
Судя по строчке кода, это вызов написанной нами функции print_vector(5) с аргументом 5.

Следом за ней второй вызов:

File "solution.py", line 2, in print_vector
  for coord in vector:

Этот вызов происходит внутри функции print_vector, содержащейся в файле «solution.py».
Вызов находится в строке 2.

Сама же ошибка имеет вид:

TypeError: 'int' object is not iterable

Как и в первом примере, сообщение об ошибке содержит её тип и подсказку.
В нашем случае произошла ошибка типа.
В подсказке же указано, что объект типа int не является итерируемым, т.е. таким объектом, который нельзя использовать в цикле for.

Итог:

$ python3 solution.py
Traceback (most recent call last):
  File "solution.py", line 5, in <module>
    print_vector(5)
  File "solution.py", line 2, in print_vector
    for coord in vector:
TypeError: 'int' object is not iterable

В нашем коде возникла ошибка.
Её вызвала последовательность вызовов.
Первый вызов произошел непосредственно из модуля — в строке 5 происходит вызов функции print_vector(5).
Внутри этой функции ошибка возникла в строчке 2, содержащей проход по циклу.
Сообщение об ошибке означает, что итерироваться по объекту типа int нельзя.
В нашем случае мы вызвали функцию print_vector от числа (от 5).

Некоторые ошибки с примерами кода

Ошибки в синтаксисе

Наиболее частая ошибка, которая возникает в программах на Python — SyntaxError: когда какое-то утверждение записано не по правилам языка, например:

$ python3
>>> print "hello"
  File "<stdin>", line 1
    print "hello"
                ^
SyntaxError: Missing parentheses in call to 'print'. Did you mean print("hello")?

Тот же тип ошибки возникнет, если забыть поставить двоеточие в цикле:

$ python3
>>> for i in range(5)
  File "<stdin>", line 1
    for i in range(5)
                ^
SyntaxError: invalid syntax

При неправильном использовании пробелов и табуляций в начале строки возникает IndentationError:

$ python3
>>> for i in range(5):
    print(i)
  File "<stdin>", line 2
    print(i)
        ^
IndentationError: expected an indented block

А теперь посмотрим, что будет, если в первой строке цикла воспользоваться пробелами, а во второй — табуляцией:

$ python3
>>> for i in range(5):
        print(i) # здесь пробелы
        print(i**2) # здесь табуляция
    File "<stdin>", line 3
      print(i**2)
                ^
TabError: inconsistent use of tabs and spaces in indentation

NameError возникает при обращении к несуществующей переменной:

$ python3
>>> words = "Hello"
>>> word
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'word' is not defined

Ошибки в логике

Напишем простую программу на деление с остатком и сохраним как sample.py:

n = input()
m = input()
print(n % m)

и запустим её:

$ python3 sample.py
5
3
Traceback (most recent call last):
  File "sample.py", line 3, in <module>
    print(n % m)
TypeError: not all arguments converted during string formatting

Возникла ошибка TypeError, которая сообщает о неподходящем типе данных. Исправим программу:

n = int(input())
m = int(input())
print(n % m)

запустим на неподходящих данных:

$ python3 sample.py
xyz
Traceback (most recent call last):
  File "sample.py", line 1, in <module>
    n = int(input())
ValueError: invalid literal for int() with base 10: 'xyz'

Возникнет ValueError.
Эту ошибку ещё можно воспринимать как использование значения вне области допустимых значений (ОДЗ).

Теперь запустим программу на числовых данных:

$ python3 sample.py
1
0
Traceback (most recent call last):
  File "sample.py", line 3, in <module>
    print(n % m)
ZeroDivisionError: integer division or modulo by zero

При работе с массивами нередко возникает ошибка IndexError. Она возникает при выходе за пределы массива:

$ python3
>>> L1 = [1, 2, 3]
>>> L1[3]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

Что будет, если вызвать бесконечную рекурсию? Опишем её в программе endless.py

def noend():
    print("Hello!")
    noend()
noend()

Через некоторое время после запуска возникнет RecursionError:

Traceback (most recent call last):
  File "endless.py", line 4, in <module>
    noend()
  File "endless.py", line 3, in noend
    noend()
  File "endless.py", line 3, in noend
    noend()
  File "endless.py", line 3, in noend
    noend()
  [Previous line repeated 993 more times]
  File "endless.py", line 2, in noend
    print("Hello!")
RecursionError: maximum recursion depth exceeded while calling a Python object

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

Понравилась статья? Поделить с друзьями:
  • File source async output ошибка
  • File pro ошибка при чтении сертификата
  • File or directory does not exist что ошибка
  • File not found res ошибка
  • File not found exception ошибка