开个贴,用于记录平时经常碰到的Python的错误同时对导致错误的原因进行分析,并持续更新,方便以后查询,学习。
知识在于积累嘛!微笑
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
错误:
复制代码代码如下:
>>> def f(x, y):
print x, y
>>> t = ('a', 'b')
>>> f(t)
Traceback (most recent call last):
File "", line 1, in
f(t)
TypeError: f() takes exactly 2 arguments (1 given)
【错误分析】不要误以为元祖里有两个参数,将元祖传进去就可以了,实际上元祖作为一个整体只是一个参数,
实际需要两个参数,所以报错。必需再传一个参数方可.
复制代码代码如下:
>>> f(t, 'var2')
('a', 'b') var2
更常用的用法: 在前面加*,代表引用元祖
复制代码代码如下:
>>> f(*t)
'a', 'b'
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
错误:
复制代码代码如下:
>>> def func(y=2, x):
return x + y
SyntaxError: non-default argument follows default argument
【错误分析】在C++,Python中默认参数从左往右防止,而不是相反。这可能跟参数进栈顺序有关。
复制代码代码如下:
>>> def func(x, y=2):
return x + y
>>> func(1)
3
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
错误:
复制代码代码如下:
>>> D1 = {'x':1, 'y':2}
>>> D1['x']
1
>>> D1['z']
Traceback (most recent call last):
File "", line 1, in
D1['z']
KeyError: 'z'
【错误分析】这是Python中字典键错误的提示,如果想让程序继续运行,可以用字典中的get方法,如果键存在,则获取该键对应的值,不存在的,返回None,也可打印提示信息.
复制代码代码如下:
>>> D1.get('z', 'Key Not Exist!')
'Key Not Exist!'
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
错误:
复制代码代码如下:
>>> from math import sqrt
>>> exec "sqrt = 1"
>>> sqrt(4)
Traceback (most recent call last):
File "", line 1, in
sqrt(4)
TypeError: 'int' object is not callable
【错误分析】exec语句最有用的地方在于动态地创建代码字符串,但里面存在的潜在的风险,它会执行其他地方的字符串,在CGI中更是如此!比如例子中的sqrt = 1,从而改变了当前的命名空间,从math模块中导入的sqrt不再和函数名绑定而是成为了一个整数。要避免这种情况,可以通过增加in ,其中就是起到放置代码字符串命名空间的字典。
复制代码代码如下:
>>> from math import sqrt
>>> scope = {}
>>> exec "sqrt = 1" in scope
>>> sqrt(4)
2.0
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
错误:
复制代码代码如下:
>>> seq = [1, 2, 3, 4]
>>> sep = '+'
>>> sep.join(seq)
Traceback (most recent call last):
File "", line 1, in
sep.join(seq)
TypeError: sequence item 0: expected string, int found
【错误分析】join是split的逆方法,是非常重要的字符串方法,但不能用来连接整数型列表,所以需要改成:
复制代码代码如下:
>>> seq = ['1', '2', '3', '4']
>>> sep = '+'
>>> sep.join(seq)
'1+2+3+4'
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
错误:
复制代码代码如下:
>>> print r'C:\Program Files\foo\bar\'
SyntaxError: EOL while scanning string literal
【错误分析】Python中原始字符串以r开头,里面可以放置任意原始字符,包括\,包含在字符中的\不做转义。
但是,不能放在末尾!也就是说,最后一个字符不能是\,如果真 需要的话,可以这样写:
复制代码代码如下:
>>> print r'C:\Program Files\foo\bar' "\\"
C:\Program Files\foo\bar\
>>> print r'C:\Program Files\foo\bar' + "\\"
C:\Program Files\foo\bar\
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
代码:
复制代码代码如下:
bad = 'bad'
try:
raise bad
except bad:
print 'Got Bad!'
错误:
复制代码代码如下:
>>>
Traceback (most recent call last):
File "D:\Learn\Python\Learn.py", line 4, in
raise bad
TypeError: exceptions must be old-style classes or derived from BaseException, not str