Common error prompt handling in python

Common errors in python are

  1. NameError variable name error
  2. IndentationError code indentation error
  3. AttributeError object attribute error
  4. TypeError type error
  5. IOError input and output error
  6. KeyError dictionary key value error explained in detail

1.NameError variable name error report:

python学习交流群:660193417###
>>> print a

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

NameError: name 'a' is not defined

Solution:
first assign a value to a. to use it. In the actual code writing process, when a NameError error is reported, check whether the variable is assigned a value, or whether there is a case inconsistency error, or accidentally write the variable name wrong. Note: In Python, there is no need to display the variable declaration statement, the variable is automatically declared the first time it is assigned a value.

>>> a=1

>>> print a

1

2.IndentationError code indentation error
code

python学习交流群:660193417###
a=1b=2

if a<b:

print a

Error :

IndentationError: expected an indented block

Reason:
wrong indentation, python's indentation is very strict, multiple spaces at the beginning of the line, and less spaces will result in an error. This is a common mistake made by newbies due to unfamiliarity with python coding rules. Code blocks like def, class, if, for, while etc. need to be indented. The indentation is four spaces wide. It should be noted that the width of the space represented by the tab character (tab key) in different text editors is different. If the code needs to be read and written across platforms or editors, it is recommended not to use tab characters. .
solution

a=1b=2

if a<b:

    print a

3. AttributeError object attribute error
error:

python学习交流群:660193417###
>>> import sys

>>> sys.Path

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

AttributeError: 'module' object has no attribute 'Path'

Reason:
The sys module has no Path attribute.
Python is case sensitive, and Path and path represent different variables.
Change Path to path.

>>> sys.path

['',  '/usr/lib/python2.6/site-packages']

Guess you like

Origin blog.csdn.net/m0_67575344/article/details/124453553