python编码错误

错误:

【错误分析】第二个参数必须为类,否则会报TypeError,所以正确的应该是这样的:

但如果第二个参数是类型对象,则不会报上面的错误,是允许的,比如说:

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

错误:

【错误分析】这个涉及到调用顺序问题,即解析方法的MRO调用顺序,在Python2.7版本之后,这样调用会报错,

必须是子类先放前面,然后才是父类.如下所示,方不会报错.

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

错误:

【错误分析】foo()未带参数self,也未带cls参数,属于类的静态方法,类的静态方法调用,实例不能直接调用,需要再声明一个静态方法

或者通过@staticmethod来调用

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

错误:

【错误分析】__dict__是实例的特殊属性,但在内建属性中,不存在__dict__属性,一般的情况是:

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

错误:

【错误分析】如果定义了构造器,它不应当返回任何对象,因为实例对象是自动在实例化调用后返回的。相应地,__init__()就不应当返回任何对象(应当为None);否则就可能出现冲突,因为只能返回实例。试着返回非None的任何其他对象都会导致TypeError异常

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

错误:

  1. >>> def f(x, y):
  2. print x, y
  3. >>> t = (‘a‘, ‘b‘)
  4. >>> f(t)
  5. Traceback (most recent call last):
  6. File "<pyshell#65>", line 1, in <module>
  7. f(t)
  8. TypeError: f() takes exactly 2 arguments (1 given)

【错误分析】不要误以为元祖里有两个参数,将元祖传进去就可以了,实际上元祖作为一个整体只是一个参数,

实际需要两个参数,所以报错。必需再传一个参数方可.

  1. >>> f(t, ‘var2‘)
  2. (‘a‘, ‘b‘) var2

更常用的用法: 在前面加*,代表引用元祖

  1. >>> f(*t)
  2. ‘a‘, ‘b‘

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

错误:

  1. >>> def func(y=2, x):
  2. return x + y
  3. SyntaxError: non-default argument follows default argument

【错误分析】在C++,Python中默认参数从左往右防止,而不是相反。这可能跟参数进栈顺序有关。

  1. >>> def func(x, y=2):
  2. return x + y
  3. >>> func(1)
  4. 3

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

错误:

  1. >>> D1 = {‘x‘:1, ‘y‘:2}
  2. >>> D1[‘x‘]
  3. 1
  4. >>> D1[‘z‘]
  5. Traceback (most recent call last):
  6. File "<pyshell#185>", line 1, in <module>
  7. D1[‘z‘]
  8. KeyError: ‘z‘

【错误分析】这是Python中字典键错误的提示,如果想让程序继续运行,可以用字典中的get方法,如果键存在,则获取该键对应的值,不存在的,返回None,也可打印提示信息.

  1. >>> D1.get(‘z‘, ‘Key Not Exist!‘)
  2. ‘Key Not Exist!‘

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

错误:

  1. >>> from math import sqrt
  2. >>> exec "sqrt = 1"
  3. >>> sqrt(4)
  4. Traceback (most recent call last):
  5. File "<pyshell#22>", line 1, in <module>
  6. sqrt(4)
  7. TypeError: ‘int‘ object is not callable

【错误分析】exec语句最有用的地方在于动态地创建代码字符串,但里面存在的潜在的风险,它会执行其他地方的字符串,在CGI中更是如此!比如例子中的sqrt = 1,从而改变了当前的命名空间,从math模块中导入的sqrt不再和函数名绑定而是成为了一个整数。要避免这种情况,可以通过增加in <scope>,其中<scope>就是起到放置代码字符串命名空间的字典。

  1. >>> from math import sqrt
  2. >>> scope = {}
  3. >>> exec "sqrt = 1" in scope
  4. >>> sqrt(4)
  5. 2.0

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

错误:

  1. >>> seq = [1, 2, 3, 4]
  2. >>> sep = ‘+‘
  3. >>> sep.join(seq)
  4. Traceback (most recent call last):
  5. File "<pyshell#25>", line 1, in <module>
  6. sep.join(seq)
  7. TypeError: sequence item 0: expected string, int found

【错误分析】join是split的逆方法,是非常重要的字符串方法,但不能用来连接整数型列表,所以需要改成:

  1. >>> seq = [‘1‘, ‘2‘, ‘3‘, ‘4‘]
  2. >>> sep = ‘+‘
  3. >>> sep.join(seq)
  4. ‘1+2+3+4‘

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

错误:

  1. >>> print r‘C:\Program Files\foo\bar\‘
  2. SyntaxError: EOL while scanning string literal

【错误分析】Python中原始字符串以r开头,里面可以放置任意原始字符,包括\,包含在字符中的\不做转义。

但是,不能放在末尾!也就是说,最后一个字符不能是\,如果真 需要的话,可以这样写:

  1. >>> print r‘C:\Program Files\foo\bar‘ "\\"
  2. C:\Program Files\foo\bar\
  3. >>> print r‘C:\Program Files\foo\bar‘ + "\\"
  4. C:\Program Files\foo\bar\

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

代码:

  1. bad = ‘bad‘
  2. try:
  3. raise bad
  4. except bad:
  5. print ‘Got Bad!‘

错误:

  1. >>>
  2. Traceback (most recent call last):
  3. File "D:\Learn\Python\Learn.py", line 4, in <module>
  4. raise bad
  5. TypeError: exceptions must be old-style classes or derived from BaseException, not str

【错误分析】因所用的Python版本2.7,比较高的版本,raise触发的异常,只能是自定义类异常,而不能是字符串。所以会报错,字符串改为自定义类,就可以了。

  1. class Bad(Exception):
  2. pass
  3. def raiseException():
  4. raise Bad()
  5. try:
  6. raiseException()
  7. except Bad:
  8. print ‘Got Bad!‘

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

  1. class Super:
  2. def method(self):
  3. print "Super‘s method"
  4. class Sub(Super):
  5. def method(self):
  6. print "Sub‘s method"
  7. Super.method()
  8. print "Over..."
  9. S = Sub()
  10. S.method()

执行上面一段代码,错误如下:

  1. >>>
  2. Sub‘s method
  3. Traceback (most recent call last):
  4. File "D:\Learn\Python\test.py", line 12, in <module>
  5. S.method()
  6. File "D:\Learn\Python\test.py", line 8, in method
  7. Super.method()
  8. TypeError: unbound method method() must be called with Super instance as first argument (got nothing instead)

【错误分析】Python中调用类的方法,必须与实例绑定,或者调用自身.

ClassName.method(x, ‘Parm‘)

ClassName.method(self)

所以上面代码,要调用Super类的话,只需要加个self参数即可。

  1. class Super:
  2. def method(self):
  3. print "Super‘s method"
  4. class Sub(Super):
  5. def method(self):
  6. print "Sub‘s method"
  7. Super.method(self)
  8. print "Over..."
  9. S = Sub()
  10. S.method()
  11. #输出结果
  12. >>>
  13. Sub‘s method
  14. Super‘s method
  15. Over...

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

  1. >>> reload(sys)
  2. Traceback (most recent call last):
  3. File "<stdin>", line 1, in <module>
  4. NameError: name ‘sys‘ is not defined

【错误分析】reload期望得到的是对象,所以该模块必须成功导入。在没导入模块前,不能重载.

  1. >>> import sys
  2. >>> reload(sys)
  3. <module ‘sys‘ (built-in)>

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

  1. >>> def f(x, y, z):
  2. return x + y + z
  3. >>> args = (1,2,3)
  4. >>> print f(args)
  5. Traceback (most recent call last):
  6. File "<pyshell#6>", line 1, in <module>
  7. print f(args)
  8. TypeError: f() takes exactly 3 arguments (1 given)

【错误分析】args是一个元祖,如果是f(args),那么元祖是作为一个整体作为一个参数

*args,才是将元祖中的每个元素作为参数

  1. >>> f(*args)
  2. 6

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

  1. >>> def f(a,b,c,d):
  2. ...   print a,b,c,d
  3. ...
  4. >>> args = (1,2,3,4)
  5. >>> f(**args)
  6. Traceback (most recent call last):
  7. File "<stdin>", line 1, in <module>
  8. TypeError: f() argument after ** must be a mapping, not tuple

【错误分析】错误原因**匹配并收集在字典中所有包含位置的参数,但传递进去的却是个元祖。

所以修改传递参数如下:

  1. >>> args = {‘a‘:1,‘b‘:2,‘c‘:3}
  2. >>> args[‘d‘] = 4
  3. >>> f(**args)
  4. 1 2 3 4

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

【错误分析】在函数hider()内使用了内置变量open,但根据Python作用域规则LEGB的优先级:

先是查找本地变量==》模块内的其他函数==》全局变量==》内置变量,查到了即停止查找。

所以open在这里只是个字符串,不能作为打开文件来使用,所以报错,更改变量名即可。

可以导入__builtin__模块看到所有内置变量:异常错误、和内置方法

>>> import __builtin__
>>> dir(__builtin__)
[‘ArithmeticError‘, ‘AssertionError‘, ‘AttributeError‘,..

.........................................zip,filter,map]

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

  1. In [105]: T1 = (1)
  2. In [106]: T2 = (2,3)
  3. In [107]: T1 + T2
  4. ---------------------------------------------------------------------------
  5. TypeError                                 Traceback (most recent call last)
  6. <ipython-input-107-b105c7b32d90> in <module>()
  7. ----> 1 T1 + T2;
  8. TypeError: unsupported operand type(s) for +: ‘int‘ and ‘tuple‘

【错误分析】(1)的类型是整数,所以不能与另一个元祖做合并操作,如果只有一个元素的元祖,应该用(1,)来表示

  1. In [108]: type(T1)
  2. Out[108]: int
  3. In [109]: T1 = (1,)
  4. In [110]: T2 = (2,3)
  5. In [111]: T1 + T2
  6. Out[111]: (1, 2, 3)

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

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

【错误分析】字典中的键必须是不可变对象,如(整数,浮点数,字符串,元祖).

可用hash()判断某个对象是否可哈希

  1. >>> hash(‘string‘)
  2. -1542666171

但列表中元素是可变对象,所以是不可哈希的,所以会报上面的错误.

如果要用列表作为字典中的键,最简单的办法是:

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

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

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

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

或者说返回值为空,所以要实现反转并排序,不能并行操作,要分开来写

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

或者用下面的方法实现:

  1. In [103]: sorted(reversed([2,1,4,3]))
  2. Out[103]: [1, 2, 3, 4]

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

  1. >>> class = 78
  2. SyntaxError: invalid syntax

【错误分析】class是Python保留字,Python保留字不能做变量名,可以用Class,或klass
同样,保留字不能作为模块名来导入,比如说,有个and.py,但不能将其作为模块导入

  1. >>> import and
  2. SyntaxError: invalid syntax

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

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

【错误分析】\n默认为换行,\t默认为TAB键.

所以在D:\目录下找不到ew目录下的ext.data文件,将其改为raw方式输入即可。

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

  1. try:
  2. print 1 / 0
  3. except ZeroDivisionError:
  4. print ‘integer division or modulo by zero‘
  5. finally:
  6. print ‘Done‘
  7. else:
  8. print ‘Continue Handle other part‘
  9. 报错如下:
  10. D:\>python Learn.py
  11. File "Learn.py", line 11
  12. else:
  13. ^
  14. SyntaxError: invalid syntax

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

  1. try:
  2. print 1 / 0
  3. except ZeroDivisionError:
  4. print ‘integer division or modulo by zero‘
  5. else:
  6. print ‘Continue Handle other part‘
  7. finally:
  8. print ‘Done‘

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

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

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

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

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

  1. class JustCounter:
  2. __secretCount = 0
  3. def count(self):
  4. self.__secretCount += 1
  5. print ‘secretCount is:‘, self.__secretCount
  6. count1 = JustCounter()
  7. count1.count()
  8. count1.count()
  9. count1.__secretCount

报错如下:

  1. >>>
  2. secretCount is: 1
  3. secretCount is: 2
  4. Traceback (most recent call last):
  5. File "D:\Learn\Python\Learn.py", line 13, in <module>
  6. count1.__secretCount
  7. AttributeError: JustCounter instance has no attribute ‘__secretCount‘

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

解决办法如下:

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

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

  1. >>> print x
  2. Traceback (most recent call last):
  3. File "<stdin>", line 1, in <module>
  4. NameError: name ‘x‘ is not defined
  5. >>> x = 1
  6. >>> print x
  7. 1

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

  1. >>> t = (1,2)
  2. >>> t.append(3)
  3. Traceback (most recent call last):
  4. File "<stdin>", line 1, in <module>
  5. AttributeError: ‘tuple‘ object has no attribute ‘append‘
  6. >>> t.remove(2)
  7. Traceback (most recent call last):
  8. File "<stdin>", line 1, in <module>
  9. AttributeError: ‘tuple‘ object has no attribute ‘remove‘
  10. >>> t.pop()
  11. Traceback (most recent call last):
  12. File "<stdin>", line 1, in <module>
  13. AttributeError: ‘tuple‘ object has no attribute ‘pop‘

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

  1. >>> t = ()
  2. >>> t[0]
  3. Traceback (most recent call last):
  4. File "<stdin>", line 1, in <module>
  5. IndexError: tuple index out of range
  6. >>> l = []
  7. >>> l[0]
  8. Traceback (most recent call last):
  9. File "<stdin>", line 1, in <module>
  10. IndexError: list index out of range

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

  1. >>> if X>Y:
  2. ...  X,Y = 3,4
  3. ...   print X,Y
  4. File "<stdin>", line 3
  5. print X,Y
  6. ^
  7. IndentationError: unexpected indent
  8. >>>   t = (1,2,3,4)
  9. File "<stdin>", line 1
  10. t = (1,2,3,4)
  11. ^
  12. IndentationError: unexpected indent

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

  1. >>> f = file(‘1.txt‘)
  2. >>> f.readline()
  3. ‘AAAAA\n‘
  4. >>> f.readline()
  5. ‘BBBBB\n‘
  6. >>> f.next()
  7. ‘CCCCC\n‘

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

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

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

next()方法属于Python的魔法方法,这种方法的效果就是:逐行读取文本文件的最佳方式就是根本不要去读取。

取而代之的用for循环去遍历文件,自动调用next()去调用每一行,且不会报错

  1. for line in open(‘test.txt‘,‘r‘):
  2. print line

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

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

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

  1. >>> a,b,c,d = string
  2. >>> a,d
  3. (‘S‘, ‘M‘)
  4. #除非用切片的方式
  5. >>> a,b,c = string[0],string[1],string[2:]
  6. >>> a,b,c
  7. (‘S‘, ‘P‘, ‘AM‘)
  8. 或者
  9. >>> a,b,c = list(string[:2]) + [string[2:]]
  10. >>> a,b,c
  11. (‘S‘, ‘P‘, ‘AM‘)
  12. 或者
  13. >>> (a,b),c = string[:2],string[2:]
  14. >>> a,b,c
  15. (‘S‘, ‘P‘, ‘AM‘)
  16. 或者
  17. >>> ((a,b),c) = (‘SP‘,‘AM‘)
  18. >>> a,b,c
  19. (‘S‘, ‘P‘, ‘AM‘)
  20. 简单点就是:
  21. >>> a,b = string[:2]
  22. >>> c   = string[2:]
  23. >>> a,b,c
  24. (‘S‘, ‘P‘, ‘AM‘)

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

  1. >>> mydic={‘a‘:1,‘b‘:2}
  2. >>> mydic[‘a‘]
  3. 1
  4. >>> mydic[‘c‘]
  5. Traceback (most recent call last):
  6. File "<stdin>", line 1, in ?
  7. KeyError: ‘c‘

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

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

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

  1. File "study.py", line 3
  2. return None
  3. ^
  4. dentationError: unexpected indent

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

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

  1. >>>def A():
  2. return A()
  3. >>>A() #无限循环,等消耗掉所有内存资源后,报最大递归深度的错误
  4. File "<pyshell#2>", line 2, in A return A()RuntimeError: maximum recursion depth exceeded
  5. class Bird:
  6. def __init__(self):
  7. self.hungry = True
  8. def eat(self):
  9. if self.hungry:
  10. print "Ahaha..."
  11. self.hungry = False
  12. else:
  13. print "No, Thanks!"
  14. 该类定义鸟的基本功能吃,吃饱了就不再吃
  15. 输出结果:
  16. >>> b = Bird()
  17. >>> b.eat()
  18. Ahaha...
  19. >>> b.eat()
  20. No, Thanks!
  21. 下面一个子类SingBird,
  22. class SingBird(Bird):
  23. def __init__(self):
  24. self.sound = ‘squawk‘
  25. def sing(self):
  26. print self.sound
  27. 输出结果:
  28. >>> s = SingBird()
  29. >>> s.sing()
  30. squawk
  31. SingBird是Bird的子类,但如果调用Bird类的eat()方法时,
  32. >>> s.eat()
  33. Traceback (most recent call last):
  34. File "<pyshell#5>", line 1, in <module>
  35. s.eat()
  36. File "D:\Learn\Python\Person.py", line 42, in eat
  37. if self.hungry:
  38. AttributeError: SingBird instance has no attribute ‘hungry‘

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

  1. class SingBird(Bird):
  2. def __init__(self):
  3. self.sound = ‘squawk‘
  4. self.hungry = Ture #加这么一句
  5. def sing(self):
  6. print self.sound

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

  1. class Bird:
  2. def __init__(self):
  3. self.hungry = True
  4. def eat(self):
  5. if self.hungry:
  6. print "Ahaha..."
  7. self.hungry = False
  8. else:
  9. print "No, Thanks!"
  10. class SingBird(Bird):
  11. def __init__(self):
  12. super(SingBird,self).__init__()
  13. self.sound = ‘squawk‘
  14. def sing(self):
  15. print self.sound
  16. >>> sb = SingBird()
  17. Traceback (most recent call last):
  18. File "<pyshell#5>", line 1, in <module>
  19. sb = SingBird()
  20. File "D:\Learn\Python\Person.py", line 51, in __init__
  21. super(SingBird,self).__init__()
  22. TypeError: must be type, not classobj

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

  1. __metaclass__=type
  2. class Bird:
  3. def __init__(self):
  4. self.hungry = True
  5. def eat(self):
  6. if self.hungry:
  7. print "Ahaha..."
  8. self.hungry = False
  9. else:
  10. print "No, Thanks!"
  11. class SingBird(Bird):
  12. def __init__(self):
  13. super(SingBird,self).__init__()
  14. self.sound = ‘squawk‘
  15. def sing(self):
  16. print self.sound
  17. >>> S = SingBird()
  18. >>> S.
  19. SyntaxError: invalid syntax
  20. >>> S.
  21. SyntaxError: invalid syntax
  22. >>> S.eat()
  23. Ahaha...

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

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

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

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

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

  1. >>> X = 1;
  2. >>> Y = 2;
  3. >>> X + = Y
  4. File "<stdin>", line 1
  5. X + = Y
  6. ^
  7. SyntaxError: invalid syntax

【错误分析】增强行赋值不能分开来写,必须连着写比如说 +=, *=

  1. >>> X += Y
  2. >>> X;Y
  3. 3
  4. 2

原文地址:https://www.cnblogs.com/wzbk/p/8410805.html

时间: 2024-08-30 12:03:12

python编码错误的相关文章

python编码错误的解决办法 SyntaxError: Non-ASCII character &#39;\xe5&#39; in file

[提出问题]. 在编写Python时,当使用中文输出或注释时运行脚本,会提示错误信息: SyntaxError: Non-ASCII character '\xe5' in file ******* ---------------------------------------------------------------------------------------------------------- [分析问题]. -----------------------------------

Python编码错误的解决办法SyntaxError: Non-ASCII character &#39;\xe5&#39; in file

[现象] 在编写Python时,当使用中文输出或注释时运行脚本,会提示错误信息: SyntaxError: Non-ASCII character '\xe5' in file ******* [原因] python的默认编码文件是用的ASCII码,而你的python文件中使用了中文等非英语字符. [解决办法] 在Python源文件的最开始一行,加入一句: # coding=UTF-8(等号换为”:“也可以) 或者 # -*- coding:UTF-8 -*- 转自[http://blog.cs

Python Solve UnicodeEncodeError &#39;gbk&#39; / &#39;ascii&#39; / &#39;utf8&#39; codec can&#39;t encode character &#39;\x??&#39; in position ? 解决有关Python编码的错误

在Python中,处理中文字符一直是很令人头痛的问题,一言不合就乱码,而且引起乱码的原因也不尽相同,有时候是python本身默认的编码器设置的不对,有时候是使用的IDE的解码器不对,还有的时候是终端terminal的解码器不对,有时候同一份代码在Python2上正常运行,Python3上就不行了,反正产生乱码的原因很多,这里就列举一些博主遇到过的一些错误及其解决方案: Error 1: UnicodeEncodeError: 'gbk' codec can't encode character

python运行显示编码错误

python中运行显示编码错误一般有2种原因: 编码与译码的方式不一致 在编写Python时,当使用中文输出或注释时运行脚本,会提示错误信息: SyntaxError: Non-ASCII character '\xe5' in file ******* [原因] python解释器的默认编码文件是用的ASCII码,而你的python文件中使用了中文等非英语字符. [解决办法] 在Python源文件的最开始一行,加入一句: # coding=UTF-8(等号换为”:“也可以) 注意:等号左右两边

PYTHON编码处理-str与Unicode的区别

一篇关于str和Unicode的好文章 整理下python编码相关的内容 注意: 以下讨论为Python2.x版本, Py3k的待尝试 开始 用python处理中文时,读取文件或消息,http参数等等 一运行,发现乱码(字符串处理,读写文件,print) 然后,大多数人的做法是,调用encode/decode进行调试,并没有明确思考为何出现乱码 所以调试时最常出现的错误 错误1 Traceback (most recent call last): File "<stdin>"

python 编码问题:&#39;ascii&#39; codec can&#39;t encode characters in position 的解决方案

问题描述: Python在安装时,默认的编码是ascii,当程序中出现非ascii编码时,python的处理常常会报这样的错UnicodeDecodeError: 'ascii' codec can't decode byte 0x?? in position 1: ordinal not in range(128),python没办法处理非ascii编码的,此时需要自己设置将python的默认编码,一般设置为utf8的编码格式. 查询系统默认编码可以在解释器中输入以下命令: Python代码

PEP8 Python 编码规范

PEP8 Python 编码规范 一 代码编排 1 缩进.4个空格的缩进(编辑器都可以完成此功能),不使用Tap,更不能混合使用Tap和空格.2 每行最大长度79,换行可以使用反斜杠,最好使用圆括号.换行点要在操作符的后边敲回车.3 类和top-level函数定义之间空两行:类中的方法定义之间空一行:函数内逻辑无关段落之间空一行:其他地方尽量不要再空行. 二 文档编排 1 模块内容的顺序:模块说明和docstring-import-globals&constants-其他定义.其中import部

【Python进阶】02、python编码问题

一.ASCII.Unicode和UTF-8的区别 因为字符编码的问题而苦恼不已,于是阅读了大量的博客,再进行了一定的测试,基本搞清楚了编码问题的前因后果. 1.字符集和字符编码 计算机中储存的信息都是用二进制数表示的:而我们在屏幕上看到的英文.汉字等字符是二进制数转换之后的结果.通俗的说,按照何种规则将字符存储在计算机中,如'a'用什么表示,称为"编码":反之,将存储在计算机中的二进制数解析显示出来,称为"解码",如同密码学中的加密和解密.在解码过程中,如果使用了错

Python编码——常见的编码设置

1.查看自己电脑的python的编码设置 # -*- coding: utf8 -*- import sys, locale """ locale.getpreferredencoding() 重要参数,默认为打开本地操作系统读取的文本文件的编码方式,因操作系统而异,除非指定 sys.stdout/stdin/stderr 标准输出/输入/错误输出 PYTHONIOENCODING 变量指定 sys.getdefaultencoding() python将binary dat