Python错误汇总

开个贴,用于记录平时经常碰到的Python的错误同时对导致错误的原因进行分析,并持续更新,方便以后查询,学习。

知识在于积累嘛!

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

>>> hash(1,(2,[3,4]))

Traceback (most recent call last):
  File "<pyshell#95>", line 1, in <module>
    hash((1,2,(2,[3,4])))
TypeError: unhashable type: 'list'

【错误分析】字典中的键必须是不可变对象,如(整数,浮点数,字符串,元祖),可用hash()判断某个对象是否可哈希

>>> hash('string')
-1542666171

但列表中元素是可变对象,所以是不可哈希的,所以会报上面的错误.如果要用列表作为字典中的键,最简单的办法是:

>>> D = {}
>>> D[tuple([3,4])] = 5
>>> D
{(3, 4): 5}

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

>>> L = [2,1,4,3]
>>> L.reverse().sort()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'sort'
>>> L
[3, 4, 1, 2]

【错误分析】列表属于可变对象,其append(),sort(),reverse()会在原处修改对象,不会有返回值,或者说返回值为空,

所以要实现反转并排序,不能并行操作,要分开来写

>>> L = [2,1,4,3]
>>> L.reverse()
>>> L.sort()
>>> L
[1, 2, 3, 4]

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

>>> class = 78
SyntaxError: invalid syntax

【错误分析】class是Python保留字,Python保留字不能做变量名,可以用Class,或klass

同样,保留字不能作为模块名来导入,比如说,有个and.py,但不能将其作为模块导入

>>> import and
SyntaxError: invalid syntax

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

>>> f = open('D:\new\text.data','r')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IOError: [Errno 22] invalid mode ('r') or filename: 'D:\new\text.data'
>>> f = open(r'D:\new\text.data','r')
>>> f.read()
'Very\ngood\naaaaa'

【错误分析】\n默认为换行,\t默认为TAB键,所以在D:\目录下找不到ew目录下的ext.data文件,将其改为raw方式输入即可。

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

try:
    print 1 / 0

except ZeroDivisionError:
    print 'integer division or modulo by zero'

finally:
    print 'Done'

else:
    print 'Continue Handle other part'
报错如下:
D:\>python Learn.py
  File "Learn.py", line 11
    else:
       ^
SyntaxError: invalid syntax

【错误分析】错误原因,else, finally执行位置;正确的程序应该如下:

try:
    print 1 / 0

except ZeroDivisionError:
    print 'integer division or modulo by zero'

else:
    print 'Continue Handle other part'

finally:
    print 'Done'

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

>>> [x,y for x in range(2) for y in range(3)]
  File "<stdin>", line 1
    [x,y for x in range(2) for y in range(3)]
           ^
SyntaxError: invalid syntax

【错误分析】错误原因,列表解析中,x,y必须以数组的方式列出(x,y)

>>> [(x,y) for x in range(2) for y in range(3)]
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2)]

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

class JustCounter:
    __secretCount = 0

    def count(self):
        self.__secretCount += 1
        print 'secretCount is:', self.__secretCount

count1 = JustCounter()

count1.count()
count1.count()

count1.__secretCount

报错如下:

>>>
secretCount is: 1
secretCount is: 2

Traceback (most recent call last):
  File "D:\Learn\Python\Learn.py", line 13, in <module>
    count1.__secretCount
AttributeError: JustCounter instance has no attribute '__secretCount'    

【错误分析】双下划线的类属性__secretCount不可访问,所以会报无此属性的错误.

解决办法如下:

# 1. 可以通过其内部成员方法访问
# 2. 也可以通过访问
ClassName._ClassName__Attr
#或
ClassInstance._ClassName__Attr
#来访问,比如:
print count1._JustCounter__secretCount
print JustCounter._JustCounter__secretCount 

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

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

【错误分析】Python不允许使用未赋值变量

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

>>> t = (1,2)
>>> t.append(3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'append'
>>> t.remove(2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'remove'
>>> t.pop()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'pop'

【错误分析】属性错误,归根到底在于元祖是不可变类型,所以没有这几种方法.

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

>>> t = ()
>>> t[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: tuple index out of range
>>> l = []
>>> l[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

【错误分析】空元祖和空列表,没有索引为0的项

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

>>> if X>Y:
...  X,Y = 3,4
...   print X,Y
  File "<stdin>", line 3
    print X,Y
    ^
IndentationError: unexpected indent

>>>   t = (1,2,3,4)
  File "<stdin>", line 1
    t = (1,2,3,4)
    ^
IndentationError: unexpected indent

【错误分析】一般出在代码缩进的问题

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

>>> f = file('1.txt')
>>> f.readline()
'AAAAA\n'
>>> f.readline()
'BBBBB\n'
>>> f.next()
'CCCCC\n'

【错误分析】如果文件里面没有行了会报这种异常

>>> f.next() #
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

有可迭代的对象的next方法,会前进到下一个结果,而在一系列结果的末尾时,会引发StopIteration的异常.

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

>>> string = 'SPAM'
>>> a,b,c = string
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack

【错误分析】接受的变量少了,应该是

>>> a,b,c,d = string
>>> a,d
('S', 'M')
#除非用切片的方式
>>> a,b,c = string[0],string[1],string[2:]
>>> a,b,c
('S', 'P', 'AM')
或者
>>> a,b,c = list(string[:2]) + [string[2:]]
>>> a,b,c
('S', 'P', 'AM')
或者
>>> (a,b),c = string[:2],string[2:]
>>> a,b,c
('S', 'P', 'AM')
或者
>>> ((a,b),c) = ('SP','AM')
>>> a,b,c
('S', 'P', 'AM')

简单点就是:
>>> a,b = string[:2]
>>> c   = string[2:]
>>> a,b,c
('S', 'P', 'AM')

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

>>> mydic={'a':1,'b':2}
>>> mydic['a']
1
>>> mydic['c']
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
KeyError: 'c'

【错误分析】当映射到字典中的键不存在时候,就会触发此类异常, 或者可以,这样测试

>>> 'a' in mydic.keys()
True
>>> 'c' in mydic.keys()              #用in做成员归属测试
False
>>> D.get('c','"c" is not exist!')   #用get或获取键,如不存在,会打印后面给出的错误信息
'"c" is not exist!'

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

  File "study.py", line 3
    return None
    ^
IndentationError: unexpected indent

【错误分析】一般是代码缩进问题,TAB键或空格键不一致导致

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

>>>def A():
return A()
>>>A() #无限循环,等消耗掉所有内存资源后,报最大递归深度的错误
File "<pyshell#2>", line 2, in A return A()RuntimeError: maximum recursion depth exceeded
class Bird:
    def __init__(self):
        self.hungry = True
    def eat(self):
        if self.hungry:
            print "Ahaha..."
            self.hungry = False
        else:
            print "No, Thanks!"
该类定义鸟的基本功能吃,吃饱了就不再吃
输出结果:
>>> b = Bird()
>>> b.eat()
Ahaha...
>>> b.eat()
No, Thanks!
下面一个子类SingBird,
class SingBird(Bird):
    def __init__(self):
        self.sound = 'squawk'
    def sing(self):
        print self.sound
输出结果:
>>> s = SingBird()
>>> s.sing()
squawk
SingBird是Bird的子类,但如果调用Bird类的eat()方法时,
>>> s.eat()
Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    s.eat()
  File "D:\Learn\Python\Person.py", line 42, in eat
    if self.hungry:
AttributeError: SingBird instance has no attribute 'hungry'

【错误分析】代码错误很清晰,SingBird中初始化代码被重写,但没有任何初始化hungry的代码

class SingBird(Bird):
    def __init__(self):
        self.sound = 'squawk'
        self.hungry = Ture #加这么一句
    def sing(self):
        print self.sound

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

class Bird:
    def __init__(self):
        self.hungry = True
    def eat(self):
        if self.hungry:
            print "Ahaha..."
            self.hungry = False
        else:
            print "No, Thanks!"

class SingBird(Bird):
    def __init__(self):
        super(SingBird,self).__init__()
        self.sound = 'squawk'
    def sing(self):
        print self.sound
>>> sb = SingBird()
Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    sb = SingBird()
  File "D:\Learn\Python\Person.py", line 51, in __init__
    super(SingBird,self).__init__()
TypeError: must be type, not classobj

【错误分析】在模块首行里面加上__metaclass__=type,具体还没搞清楚为什么要加

__metaclass__=type
class Bird:
    def __init__(self):
        self.hungry = True
    def eat(self):
        if self.hungry:
            print "Ahaha..."
            self.hungry = False
        else:
            print "No, Thanks!"

class SingBird(Bird):
    def __init__(self):
        super(SingBird,self).__init__()
        self.sound = 'squawk'
    def sing(self):
        print self.sound
>>> S = SingBird()
>>> S.
SyntaxError: invalid syntax
>>> S.
SyntaxError: invalid syntax
>>> S.eat()
Ahaha...

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

>>> T
(1, 2, 3, 4)
>>> T[0] = 22
Traceback (most recent call last):
  File "<pyshell#129>", line 1, in <module>
    T[0] = 22
TypeError: 'tuple' object does not support item assignment

【错误分析】元祖不可变,所以不可以更改;可以用切片或合并的方式达到目的.

>>> T = (1,2,3,4)
>>> (22,) + T[1:]
(22, 2, 3, 4)

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

时间: 2024-10-16 18:46:14

Python错误汇总的相关文章

编程中遇到的Python错误和解决方法汇总整理

这篇文章主要介绍了自己编程中遇到的Python错误和解决方法汇总整理,本文收集整理了较多的案例,需要的朋友可以参考下 开个贴,用于记录平时经常碰到的Python的错误同时对导致错误的原因进行分析,并持续更新,方便以后查询,学习.知识在于积累嘛!微笑+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++错误: 复制代码代码如下: >>> def f(x, y):      print x, y  >>> t

编程中易犯错误汇总:一个综合案例.md

# 11编程中易犯错误汇总:一个综合案例 在上一篇文章中,我们学习了如何区分好的代码与坏的代码,如何写好代码.所谓光说不练假把式,在这篇文章中,我们就做一件事——一起来写代码.首先,我会先列出问题,然后要求读者自己写一份答案:然后,我会给出我写的代码:最后,我们还会以这个问题为例,讨论编程中常见的错误. ## 1 问题描述 在[这个](http://wiki.openhatch.org/index.php?title=Scrabble_challenge)页面中,有一道Python相关的练习题,

python错误 invalid command &#39;bdist_wheel&#39; &amp; outside environment /usr

按照网上说的执行以下命令 sudo pip install --upgrade setuptools sudo pip install --upgrade pip 结果 Not uninstalling setuptools at /usr/lib/python2.7/dist-packages, outside environment /usr 虽然有下载但更新并不成功应该跟python2/3环境有关执行以下命令 sudo apt-get install python3-pip 解决问题 参考

Python错误:TypeError:&#39;str&#39; does not support the buffer interface

在socket套接字模块进行send和recv方法时出现这种问题,是因为Python3.x和Python2.x版本变化,In python 3, bytes strings and unicodestrings are now two different types. 相互之间需要进行转换decode()和encode(). send()需要的参数为bytes类型,因此需要对str进行encode() recv()返回的是bytes类型,因此我们需要对返回的bytes进行decode()转换为s

python错误: SyntaxError: Non-ASCII character &#39;\xe5&#39; in file /home...

python中使用中文注释出现错误 SyntaxError: Non-ASCII character '\xe5' in file /home... 解决 在文件开头加入: # -*- coding: UTF-8 -*-    或者  #coding=utf-8 python错误: SyntaxError: Non-ASCII character '\xe5' in file /home...

python 错误处理

在程序运行的过程中,如果发生了错误,可以事先约定返回一个错误代码,这样,就可以知道是否有错,以及出错的原因.在操作系统提供的调用中,返回错误码非常常见.比如打开文件的函数open(),成功时返回文件描述符(就是一个整数),出错时返回-1. 用错误码来表示是否出错十分不便,因为函数本身应该返回的正常结果和错误码混在一起,造成调用者必须用大量的代码来判断是否出错: def foo(): r = some_function() if r==(-1): return (-1) # do somethin

Git各种错误汇总

1.github上版本和本地上版本冲突的方法,即提交时会提示如下错误: 解决方法,提交时采用如下代码: git push -u origin master -f 参考链接: http://blog.csdn.net/shiren1118/article/details/7761203 Git各种错误汇总

李洪强iOS开发之OC常见错误汇总

// //  main.m //  16 - 常见错误汇总 // //  Created by vic fan on 16/7/13. //  Copyright © 2016年 李洪强. All rights reserved. // OC的常见错误汇总: 1 @interface ... @end  和 @implementation ..@end 之间不能嵌套 2只有类的声明没有类的实现 3 漏写@end 4 两个类的声明顺序可以打乱,但是类的声明一定要在类的实现前面 5 成员变量没有放在

python错误解决:SyntaxError: Non-ASCII character &#39;\xd3&#39; in file crawler.py

我写的python代码中遇到编码问题:SyntaxError: Non-ASCII character '\xd3' in file crawler.py 原因:代码中有需要输出中文的部分,但是运行时出现了这个错误: 错误中提示看这个链接:http://www.python.org/peps/pep-0263.html 解决问题的方法: 如果在python中出现了非ASCII码以外的其他字符,需要在代码的开头声明字符格式 解决之一: 在程序的开头加上#-*-coding:utf-8-*- ~te