I'm not afraid of errors anymore! Python errors and their causes / solutions

One of the things you will always encounter when doing ** programming ** is ** error **. When I ran the program I wrote so hard, I got a long sentence in English that I didn't understand! I think that many people are frustrated because this error cannot be resolved. In this article, I'll tell you about the causes of errors in ** Python ** and how to resolve them.

  1. SyntaxError I think it's the first error most programming beginners encounter. Let's check one by one. This error literally translates to "** syntax error **", which means that there is a grammatical error. If you get this error, suspect that you forgot to put the closing brace ) or forget to write the colon : in the double-byte space, ʻif statement, forstatement, andwhile` statement. From here, I will explain with some examples.

1.1. Close the parentheses!

** Parentheses ** If you don't have () or forget to close it, SyntaxError: unexpected EOF while parsing I get the error.

Code that gives an error

hello_world1.py


print("Hello, world!"
# SyntaxError: unexpected EOF while parsing

In this code, I forgot to close the parentheses, so I get the error "** There is an unexpected end of the sentence **". Close the parentheses to eliminate the error.

Modified code

hello_world2.py


print("Hello, world!")
# Hello, world!

1.2. Find a hidden full-width space!

If ** double-byte space ** is mixed in the code, SyntaxError: invalid character in identifier I get the error.

Code that gives an error

circle1.py


r = 2
pi = 3.14
# ^It's hard to understand, but there is a double-byte space here.(The red underline is displayed)
print(r ** 2 * 3.14)
# SyntaxError: invalid character in identifier

Double-byte spaces are hard to find, but let's find the number of lines line (number) displayed in the error as a hint and correct it.

Modified code

circle2.py


r = 2
pi = 3.14
print(r ** 2 * 3.14)
# 12.56

1.3. Add a colon to the if, for, while statement!

If you forget to add ** colon ** : to the end of a line such as ʻif statement, forstatement,while statement, **SyntaxError: invalid syntax`** I get the error.

Code that gives an error

ten1.py


i = 10
if i == 10
	print("i is 10")
else
	print("i is not 10")
# SyntaxError: invalid syntax

ʻIf, ʻelse Add a colon to the end of each sentence to solve the problem.

Modified code

ten2.py


i = 10
if i == 10:
	print("i is 10")
else:
	print("i is not 10")
#i is 10
  1. NameError This is also a frequent error. The error is "** Called variable not found **". Make sure you have defined the variables you called and that you haven't misspelled them.

2.1. Check the name of the variable!

If the called variable is undefined or misspelled, ** NameError: name'variable name' is not defined ** I get the error.

Code that gives an error

year1.py


year = 2020
print(Year)

print(month)
# NameError: name 'Year' is not defined

Be careful of lowercase and uppercase letters. Since the program is executed from above, it is not mentioned that the variable month is not defined, but this also causes an error.

Modified code

year2.py


year = 2020
print(year)
# 2020
month = 3
print(month)
# 3
  1. TypeError As the name implies, it is "** type error **". This error occurs when you try to calculate between values of different types or specify an inappropriate type for a function argument. Use str () or ʻint () `to convert.

3.1. Let's check the calculation part!

When performing calculations or combining strings by assigning to print () or variables, the string type str and the numeric type ʻintcannot be used at the same time, and if you try to use them **TypeError: Can't convert'Type 1'object to (Type 2) implicitly` ** I get the error.

Code that gives an error

price1.py


price = 100
print("This product is" + price + "It is a circle.")
# TypeError: Can't convert 'int' object to str implicitly

Since 100, which is of type ʻint, is assigned to price, it cannot be combined with type str. In such a case, use the str ()function to convertprice to strtype. Similarly, if you want to convert astr type to a ʻint type in a numerical calculation, use the ʻint ()` function.

Modified code

price2.py


price = 100
print("This product is" + str(price) + "It is a circle.")
#This product is 100 yen.

The same is true for the arguments of other functions such as len ().

  1. IndentationError The error is "** Indentation is wrong **". Depending on the editor, ** indent ** may be different, such as 2 or 4 half-width spaces, and this error may occur due to the difference. Another thing that happens is that the ʻelse is processed in the indentation of the ʻif statement.

4.1. Check the indentation!

If there is any mistake in the indent, IndentationError: unindent does not match any outer indentation level I get the error. There is only one workaround for this error. "** Check indentation **". Check if the tab key and two half-width spaces are mixed.

Code that gives an error

nine1.py


number = 99999
if number % 9 == 0:
	print("number is a multiple of 9.")
    else:
      print("number is not divisible by 9.")
#   ^^There are two half-width spaces here.
# IndentationError: unindent does not match any outer indentation level

Make sure you have one indent. Also, let's get ʻelse` out.

Modified code

nine2.py


number = 99999
if number % 9 == 0:
    print("number is a multiple of 9.")
else:
    print("number is not divisible by 9.")
#number is a multiple of 9.
  1. IndexError I often come across it when dealing with lists and strings. The error is "** A non-existent index number is specified ". Don't forget that " index numbers start with 0 ** ".

5.1. Check the index number!

When specifying an element of list or str, if you specify an index number that does not exist ** ʻIndexError: (type) index out of range` ** I get the error.

Code that gives an error

abc1.py


l = ["a","b","c"]
print(l[3])
# IndexError: list index out of range

The index number of the third element will be 2 instead of 3. Note that the index number of the first element is 0. The rightmost element can also be specified with -1.

Modified code

abc2.py


l = ["a","b","c"]
print(l[2])
# c
  1. ImportError When importing a ** standard library ** or ** package **, this is an error that occurs when trying to import a module or object that does not exist. Check for misspellings.

6.1. Check the module name!

If you call a module that does not exist (or the object specified by from import), ʻImportError: No module named'specified module'` I get the error.

Code that gives an error

math1.py


import maths
print(maths.sqrt(2))
# ImportError: No module named 'maths'

The maths module does not exist. Let's rewrite it as math.

Modified code

math2.py


import math
print(math.sqrt(2))
# 1.4142135623730951

★ Addition

When I ran the error code in the Python 3.8.2 environment, ModuleNotFoundError: No module named 'maths' I got an error message. The above error was displayed in Python3.4.3, so it may be different depending on the version, but I don't think there is any particular problem.

Recommended Posts

I'm not afraid of errors anymore! Python errors and their causes / solutions
[Python] Type Error: Summary of error causes and remedies for'None Type'
The websocket of toio (nodejs) and python / websocket do not connect.
[Tips] Problems and solutions in the development of python + kivy
Source installation and installation of Python
I'm thinking of studying Python
(One of the solutions) when pyenv install on macOS causes BUILD FAILED and Python installation fails.
Environment construction of python and opencv
The story of Python and the story of NaN
Installation of SciPy and matplotlib (Python)
This and that of python properties
Coexistence of Python2 and 3 with CircleCI (1.0)
Summary of Python indexes and slices
Reputation of Python books and reference books