[Python] Understand the content of error messages

background

Although it is a memorandum for myself to learn Python, here is a summary of how to read error messages.

I would like to take this opportunity to thank you for solving the problem by borrowing the wisdom of our predecessors, and I am very sorry to say that I will summarize it here as my own memo.

Development environment

Error message

1. NameError

1-1.

--Caused by miss typing. It also happens with the difference between uppercase and lowercase letters.

python


prlnt("Hello World !")    #Wrong...print→prlnt

print("Hello World !")    #Positive

Terminal


Traceback (most resent call last):
    file "c:/~/sample.py", line 1, in <module>
        pilnt("Hello World !")
NameError: name 'Pilnt' is not defined

[Translation] Name error in module in last last call: The name "pilnt" on the first line is undefined.  ↓ ** "I made a misspelling! 』** That means.

1-2.

--Occurs when a function call is made before the function definition.

python


print(cost(100000))        #Wrong...Calling cost before definition

def cost(bill):
    return int(bill * 1.1)

Terminal


NameError: name 'cost' id not defined

[Translation] Name error occurred: "cost" is not defined.  ↓ ** "I haven't figured out or understood the function" cost "yet" **.

2. SyntaxError

――It happens due to a mistake in grammar.

2-1.

python


print("Hello World !)     #Wrong...Forget closing quotes

print("Hello World !")    #Positive

Terminal


SyntaxError: EOL while scaning stringliteral

[Translation] A syntax error occurred: An End Of Line was found while scanning a string literal.  ↓ ** "I thought it was a character string, but it ended up at the end of the line! ?? Fine? 』** That means.

2-2.

python


print( Hello World ! )    #Wrong...Forget quotes

print("Hello World !")    #Positive

Terminal


SyntaxError: invalid character in identifier

[Translation] A syntax error has occurred: An invalid character was found in the identifier.  ↓ ** "I thought it was a variable or a function (because it's not enclosed in quotes), but don't use"! "~" **.


Note
The "!" (Exclamation mark) is a character that cannot be used as the name of a variable or function. For this reason, it has been pointed out as an illegal character.

2-3.

python


ifheight > 180:     #Wrong...There is no half-width space immediately after if

if height > 180:    #Positive

Terminal


SyntaxError: invalid systax

[Translation] Grammar error occurred: Illegal grammar.  ↓ ** "You can't write like that" **.

3. TypeError

--Occurs when there is a problem with the data type.

python


print(5 + "Sheet")        #Wrong...5(Numerical value)When,"Sheet"(String)I tried to combine with the + operator, but I can't concatenate because they are different.

print("5" + "Sheet")      #Positive...Match the type to the str type
print(str(5) + "Sheet")   #Positive...Same as above

Terminal


TypeError: unsupporter operand type(s) for +: 'int' and 'str'

[Translation] Type error occurs: The + operator does not support the type of the operand.  ↓ ** "Since the data type is different between int and str, we can't process them together" **.

4. IndentaionError

--This happens when there is no nested indentation for if, for statement, function, etc., or when there is a gap.

python


if counter > 10:
break               #Wrong...No indentation

if counter > 10:
    break           #Positive

Terminal


IndentationError: expected an indented block

[Translation] Indent error occurs: Predicts that an indented block is needed.  ↓ ** "I haven't indented, but I need indentation ~" **.

5. ValueError

--This happens when a character string containing non-numeric characters is used as an argument of the int function.

--Occurs when an unsupported data type is passed to a function.

Terminal


ValueError: invalid literal for int() with base 10: 'xxxxxxx'

[Translation] Value error occurred: Illegal literal: string "xxxxxxx" for int function with argument base 10.  ↓ ** "I'm putting a character string to convert in decimal! 』** That means.

6. ModuleNotFoundError

--Occurs when the module cannot be imported. (Mainly due to typos)

python


import xxxxxxxx

Terminal


ModuleNotFoundError: No module named 'xxxxxxxx'    #I can't find the module name "xxxxxxxx"

[Translation] Module not found error occurred: There is no module named "xxxxxxxx".  ↓ ** "There is no module named" xxxxxxxx "! 』** That means.

8. ZeroDivisionError

--What happens when you divide by so-called "zero"

python


10 + 10 + 10 + 10 * 0 + 10 + 10 / 0 + 10

Terminal


ZeroDivisionError: division by zero

[Translation] Zero division error occurred: Divided by zero.  ↓ (As it is) ** "It's a zero split! 』** That means.

9. KeyboradInterrupt

--It happens when you stop the infinite loop by pressing "ctrl" + "C" keys.

Terminal


Traceback (most resent call last):
    file "c:/~/sample.py", line 120, in <module>
        counter += 1
KeyboardInterruput

[Translation] I got an interrupt from the keyboard.  ↓ ** "I stopped the program by inputting an interrupt from the keyboard! 』** That means.


(Editor's note)

I have collected and summarized the errors that I often encounter. First of all, I want to understand the content, cause and reason of a simple error so that I will not panic when an error occurs when programming complicatedly.

VS Code seems to have an extension that checks the grammar in real time, so I'll try various things.

Recommended Posts

[Python] Understand the content of error messages
[Python3] Understand the basics of Beautiful Soup
[Python3] Understand the basics of file operations
the zen of Python
About the ease of Python
14 quizzes to understand the surprisingly confusing scope of Python
Understand the status of data loss --Python vs. R
About the features of Python
The Power of Pandas: Python
Python error messages are concrete and easy to understand "ga" (SyntaxError on the closing side of triple "" "comments)
Make the display of Python module exceptions easier to understand
[Python: UnicodeDecodeError] One of the error solutions when reading CSV
The story of Python and the story of NaN
[Python] The stumbling block of import
First Python 3 ~ The beginning of repetition ~
Understand the contents of sklearn's pipeline
Existence from the viewpoint of Python
pyenv-change the python version of virtualenv
Change the Python version of Homebrew
[Python] Understanding the potential_field_planning of Python Robotics
Review of the basics of Python (FizzBuzz)
About the basics list of Python basics
Learn the basics of Python ① Beginners
[python] A note that started to understand the behavior of matplotlib.pyplot
Check the behavior of destructor in Python
The story of an error in PyOCR
Understand the benefits of the Django Rest Framework
Pass the path of the imported python module
Check the existence of the file with python
About the virtual environment of python version 3.7
What is the cause of the following error?
[Python3] Rewrite the code object of the function
I didn't know the basics of Python
The result of installing python in Anaconda
[Python] Try pydash of the Python version of lodash
[python] Checking the memory consumption of variables
Check the path of the Python imported module
The story of manipulating python global variables
[python] [meta] Is the type of python a type?
The basics of running NoxPlayer in Python
Understand the "temporary" part of UNIX / Linux
Pandas of the beginner, by the beginner, for the beginner [Python]
The Python project template I think of.
In search of the fastest FizzBuzz in Python
Python Basic Course (at the end of 15)
Set the process name of the Python program
[Python] Get the character code of the file
The story of blackjack A processing (python)
Intuitively learn the reshape of Python np
Python Note: The secret role of commas
Learning notes from the beginning of Python 2
Japanese translation: PEP 20 --The Zen of Python
Get the contents of git diff from python
[Python] Read the source code of Bottle Part 2
Introduction of Python
[python] Check the elements of the list all, any
The story of low learning costs for Python
[Python] Sort the list of pathlib.Path in natural sort
Prepare the execution environment of Python3 with Docker
Summary of the differences between PHP and Python
2016 The University of Tokyo Mathematics Solved with Python