在编写并调试Python程序的过程中,总会遇到这样或那样的错误,其中绝大多数错误都是由于用户粗心或语法错误引起的。本文将详细讲解排查Python程序错误的知识。
Python 2升级Python 3发生的错误
1 print变成了print()
1>>> i = 1
2>>> print 'Python' 'is', 'number', i
3Pythonis number 1
1>>> i = 1
2>>> print('Python' 'is', 'number', i)
3Pythonis number 1
2 raw_input变成了input
1name = input('What is your name?\n') #python3版本的代码
2name = raw_input('What is your name?\n') # python2版本的代码
3 整数及除法的问题
1batch = 200
2for x in range(len(order_nos) / batch + 1):
3 # do something
1>>>1/2 #Python 2版本中的结果是0
2>>>1/2 #Python 3版本中结果是0.5,这样比较合理
4 异常处理大升级
1except Exception, identifier
1except Exception as identifier
1except ValueError, e: # Python 2处理单个异常
2except (ValueError, TypeError), e: # Python 2处理多个异常
1except ValueError as e: # Python3处理单个异常
2except (ValueError, TypeError) as e: # Python3处理多个异常
1raise Exception, args
1raise Exception(args)
1raise ValueError, e # Python 2.x 的方法
2raise ValueError(e) # Python 3.x 的方法
5 解决“NameError: name ‘xrange’ is not defined”错误提示
6 解决“name 'reload' is not defined和AttributeError: module 'sys' has no att”错误提示
1import importlib
2importlib.reload(sys)
7 解决“python unicode is not defined”错误提示
8 解决“AttributeError: 'dict' object has no attribute 'has_key'”错误提示
1>>> d={}
2>>> d.has_key('name')
3Traceback (most recent call last):
4 File "<pyshell#1>", line 1, in <module>
5 d.has_key('name')
6AttributeError: 'dict' object has no attribute 'has_key'
1>>> d={}
2>>> 'name' in d
3True
9 解决“ImportError: No module named urllib2”错误提示
常 见 错 误
1 解决“IndentationError:excepted an indented bloc”错误提示
2 解决“no module named XX”错误提示
1pip install ww
3 解决“TypeError: 'tuple' object cannot be interpreted as an integer”错误提示
1t=('a','b','c')
2 for i in range(t):
3 print(t[i])
4 解决“IOError: File not open for writing”错误提示
1>>> f=open("hello.py")
2>>> f.write("test")
3Traceback (most recent call last):
4File "<stdin>", line 1, in <module>
5IOError: File not open for writing
1>>> f=open("hello.py",'w+')
2>>> f.write("test")
5 解决“SyntaxError:invalid syntax”错误提示
1if spam == 42 print('Hello!')
6 解决“TypeError: 'str' object does not support item assignment”错误提示
1spam = 'I have a pet cat.'
2spam[13] = 'r' print(spam)
1spam = 'I have a pet cat.'
2spam = spam[:13] + 'r' + spam[14:] print(spam)
7 解决“TypeError: Can't convert 'int' object to str implicitly”错误提示
1numEggs = 12
2print('I have ' + numEggs + ' eggs.')
1numEggs = 12
2print('I have ' + str(numEggs) + ' eggs.')
1numEggs = 12
2print('I have %s eggs.' % (numEggs))
8 错误的使用类变量
1>>> class A(object):
2 x = 1
3>>> class B(A):
4 pass
5>>> class C(A):
6 pass
7>>> print(A.x, B.x, C.x)
81 1 1
9>>> B.x = 2
10>>> print(A.x, B.x, C.x)
111 2 1
12>>> A.x = 3
13>>> print(A.x, B.x, C.x)
143 2 3
9 错误地理解Python的作用域
1x = 10
2def foo():
3 x += 1
4 print(x)
5foo()
6
7Traceback (most recent call last):
8 File "<pyshell#62>", line 1, in <module>
9 foo()
10 File "<pyshell#61>", line 2, in foo
11 x += 1
12UnboundLocalError: local variable 'x' referenced before assignment
1>>> lst = [1,2,3] # 给列表lst赋值
2>>> lst.append(4) # lst后边append一个元素4
3>>> lst
4[1, 2, 3, 4]
5>>> lst += [5] # 两个列表合并
6>>> lst
7[1, 2, 3, 4, 5]
8>>>
9def foo1():
10 lst.append(6) # 函数会查找外部的lst列表
11>>> foo1()
12>>> lst
13[1, 2, 3, 4, 5, 6]
14>>>
15def foo2():
16 lst += [6] # 合并列表时,不会查找外部列表,让人有些不可思议吧
17>>> foo2()
18Traceback (most recent call last):
19 File "<pyshell#82>", line 1, in <module>
20 foo2()
21 File "<pyshell#81>", line 2, in foo2
22 lst += [6]
23UnboundLocalError: local variable 'lst' referenced before assignment
python培训:http://www.baizhiedu.com/python2019
注释:本文内容来自公众号 异步图书