程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Dont ignore these common Python error messages

編輯:Python

Hey, everyone, good duck , I'm a bear cat

In the use of Python when , As a cute new person, I always carelessly fall here and there , There will be all kinds of errors when running , So write such a blog , To summarize some common mistakes in writing code and solutions .


what are you having? python I won't answer the related error report 、 Or source code information / Module installation / Women's clothing bosses are proficient in skills You can come here :(https://jq.qq.com/?_wv=1027&k=2Q3YTfym) Or ask me at the end of the article

NameError

Report errors :

>>> print(a)
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
print(a)
NameError: name 'a' is not defined

NameError
Name error

Causes and solutions :

  • First give a assignment , To use it . When there is a NameError when , The vast majority of cases are not unassigned , Instead, we misspell words , Or case did not notice . So go back and check what's wrong .

SyntaxErrorError

Report errors :

# error 1
>>> a = 1
>>> if a:
print(1)
SyntaxError: expected an indented block
# error 2
>>> if a<b :
SyntaxError: invalid character in identifier
# error 3
>>> print('a)
SyntaxError: EOL while scanning string literal

SyntaxError
Grammar mistakes , Wrong code form

Causes and solutions :

  • error 1: There is no indentation or the indentation format is wrong . The most common problem is Tab and Space The mix of . In fact, changing lines in most editors will automatically fill the indentation , If you're really not sure , You can press it manually Tab Or knock 4 Next Space( The latter is more recommended ). Bear in mind Tab and Space Don't press at the same time or mix multiple presses .
  • error 2: In most cases, this error occurs because Chinese punctuation is mixed when writing code , Inadvertently pressed Shift Switch to Chinese characters . When typing code , Pay more attention to whether the input method has been changed accidentally
  • error 3: There is an error 3, It's really very, very careless . It usually occurs when the quotation marks are asymmetric or missing . At this time, you should check where the color of your code is a little strange . In most editors , Enter a single quotation mark , If there is no other quotation mark corresponding to it ,")" The color of the code or the color of the code will look strange

AttributeError

Report errors :

>>> a = list()
>>> a.add('1')
Traceback (most recent call last):
File "<pyshell#21>", line 1, in <module>
a.add('1')
AttributeError: 'list' object has no attribute 'add'

AttributeError
Assignment exception

Causes and solutions :

  • This error is mainly due to the mixed use of grammar . As in the above example :a It's an empty list , Adding elements to the list is append, This application a.append(‘1’). and a.add() Is used to add elements to a collection , This mixture of grammar , Led to AttributeError.

TypeError

Report errors :

# error 1
>>>a = input('Enter a number:')
>>>print(a/2)
Enter a number:1
Traceback (most recent call last):
File "C:\Users\acer\Desktop\ test 1.py", line 2, in <module>
print(a/2)
TypeError: unsupported operand type(s) for /: 'str' and 'int'
# error 2
>>> for i in range(1,2,2,3):
print(i)
Traceback (most recent call last):
File "<pyshell#29>", line 1, in <module>
for i in range(1,2,2,3):
TypeError: range expected at most 3 arguments, got 4

TypeError
Type error

Causes and solutions :

  • error 1: As in the above example ,input() The returned value is a string type , Obviously, strings cannot be directly calculated with numbers , So it's happening TypeError. The key to solving this problem is what kind of value you need . If numerical type is required , Can be found in input() with eval(), You can return numeric . If you only need integer , Add int(). And so on .
  • error 2: Wrong number of parameters .range() There can be at most three parameters (start,end,index), But I entered 4 Parameters , So there comes TypeError. This problem mainly occurs in the unfamiliar function . It can be done by help() First check the specific usage of the function , Then add appropriate parameters for use .

IndexError

Report errors :

>>> a = list()
>>> a.append('1,2,3,a,b');a
['1,2,3,a,b']
>>> a[5]
Traceback (most recent call last):
File "<pyshell#41>", line 1, in <module>
a[5]
IndexError: list index out of range
>>>

IndexError
Index error

Causes and solutions :

  • The main reason for this error is that the index does not exist or exceeds the range of the sequence . As in the above example : list a Only 5 Elements **( Bear in mind :Python The indexes in are all from 0 Start )**, therefore a[6] What needs to be returned is the 6 Elements , And all in all is 5 Elements . So this error appears . Most of the time, it's because I forgot “ from 0 Start ” This principle leads to such mistakes , Change the index value to solve .

ValueError

Report errors :

>>> a = "abc"
>>> int(a)
Traceback (most recent call last):
File "<pyshell#46>", line 1, in <module>
int(a)
ValueError: invalid literal for int() with base 10: 'abc'

ValueError
Wrong value
Causes and solutions :

The main reason for this error is that the parameter type passed to the object is inaccurate . As in the above example ,a It's a string type , and int() What needs to be passed in is numeric , Therefore, the above error occurred . It's also easy to solve , Just change the type of input value .

KeyError

Report errors :

>>> d={'a':1,'b':2,'c':3}
>>> d['a']
1
>>> d['f']
Traceback (most recent call last):
File "<pyshell#49>", line 1, in <module>
d['f']
KeyError: 'f'

KeyError
Dictionary key value error

Causes and solutions :

  • Common in dictionaries . As in the above example , Dictionaries d Only a,b,c Three keys and corresponding key values . What I want is d[‘f’], Obviously, it doesn't exist , Therefore, the error appears , It may be caused by missing keys and key values . By accessing existing key values ( Such as a,b,c) To solve .

FileNotFoundError

Report errors :

# There is no hello,py This file
>>> f = open('hello.py')
Traceback (most recent call last):
File "<pyshell#54>", line 1, in <module>
f = open('hello.py')
FileNotFoundError: [Errno 2] No such file or directory: 'hello.py'

FileNotFoundError
There are no errors in the file

Causes and solutions :

  • It is often used for processing files . An error caused by the nonexistence of the input file name . Check whether the target file exists in this directory , Or move the target to this directory before open()

ps:
How to view python The current path of the interpreter and the files in the directory :

# View directory
import os
os.getcwd()
'C:\\Users\\acer\\Desktop'
# View the files in the directory
os.listdir('C:\\Users\\acer\\Desktop')

#, And the \ The escape of . If there are multiple \ You can also escape through r, namely os.listdir(r’C:\Users\acer\Desktop’) solve .** Remember to use r after , You can't add... At the end of the sentence \

io.UnsupportedOperation

Report errors :

>>> f = open(' test 1.py')
>>> f.write("test")
Traceback (most recent call last):
File "<pyshell#56>", line 1, in <module>
f.write("test")
io.UnsupportedOperation: not writable

io.UnsupportedOperation
An error is reported for the file permission problem ( The above example is used f.write, So it's not writable

Causes and solutions :

  • open(“ test 1.py”) If the input parameter has no read-write mode parameter mode, It indicates that the default way to open the file is read-only , At this time, it is necessary to write characters , So the permission is limited , That's what makes a mistake . It can be solved by changing the mode , namely >>>
    f=open(“ test 1.py”,‘w+’).

The above is Python Some common mistakes in learning .

what are you having? python I won't answer the related error report 、 Or source code information / Module installation / Women's clothing bosses are proficient in skills You can come here :(https://jq.qq.com/?_wv=1027&k=2Q3YTfym) Or ask me at the end of the article

Today's article is like this I'm a panda See you in the next article (*◡‿◡)


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved