Python error summary and python Summary

Source: Internet
Author: User

Python error summary and python Summary

This post is used to record common Python errors and analyze the causes of the errors. It is updated continuously to facilitate future query and learning.

What is knowledge accumulation!

++ ++

In [105]: T1 = (1)In [106]: T2 = (2,3)In [107]: T1 + T2---------------------------------------------------------------------------TypeError                                 Traceback (most recent call last)<ipython-input-107-b105c7b32d90> in <module>()----> 1 T1 + T2;TypeError: unsupported operand type(s) for +: 'int' and 'tuple'
[Error Analysis] (1) is an integer, so it cannot be merged with another ancestor. If there is only one element's ancestor, use (1 , )To indicate

In [108]: type(T1)Out[108]: intIn [109]: T1 = (1,)In [110]: T2 = (2,3)In [111]: T1 + T2Out[111]: (1, 2, 3)
++ ++

>>> 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'
[Error Analysis] the keys in the dictionary must be immutable objects, such as integers, floating-point numbers, strings, and ancestor. You can use hash () to determine whether an object can be hashed.
>>> hash('string')-1542666171
However, the elements in the list are mutable objects, so they cannot be hashed, so the above error will be reported. If you want to use the list as the dictionary key, the simplest way is:
>>> 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]
[Error Analysis] The list is a mutable object. Its append (), sort (), and reverse () will modify the object in the original place, and there will be no return value, or the return value is null,
So to reverse and sort data, parallel operations are not allowed, and data must be written separately.
>>> L = [2,1,4,3]>>> L.reverse()>>> L.sort()>>> L[1, 2, 3, 4]

Or use the following method:

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

>>> class = 78SyntaxError: invalid syntax
[Error Analysis] class is a reserved word in Python. The reserved word in Python cannot be a variable name. You can use Class or klass.
Similarly, reserved words cannot be imported as module names. For example, there is an and. py word, but it cannot be imported as a module.
>>> import andSyntaxError: 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'
[Error Analysis] \ n is a line feed by default, and \ t is a TAB key by default. Therefore, ext In The ew directory cannot be found in the D: \ directory. modify the data file to raw.
++ ++
Try: print 1/0 locale t ZeroDivisionError: print 'integer division or modulo by zero 'Finally: print 'done' else: print 'continue Handle other part' error: D: \> python Learn. py File "Learn. py ", line 11 else: ^ SyntaxError: invalid syntax

[Error Analysis] Error cause: else, finally execution location; the correct program should be as follows:

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
[Error Analysis] Error cause. In list parsing, x and y must be listed as arrays (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.__secretCountcount1 = JustCounter()count1.count()count1.count()count1.__secretCount
The following error is reported:
>>> secretCount is: 1secretCount is: 2Traceback (most recent call last):  File "D:\Learn\Python\Learn.py", line 13, in <module>    count1.__secretCountAttributeError: JustCounter instance has no attribute '__secretCount'    

[Error Analysis] Double-underline class attribute _ secretCount is not accessible. Therefore, an error indicating no such attribute is reported.

The solution is as follows:

#1. can be accessed through its internal Member method #2. you can also access ClassName. _ ClassName _ Attr # Or ClassInstance. _ ClassName _ Attr #, for example, print count1. _ JustCounter _ secretCountprint JustCounter. _ JustCounter _ secretCount
++ ++
>>> print xTraceback (most recent call last):  File "<stdin>", line 1, in <module>NameError: name 'x' is not defined>>> x = 1>>> print x1
[Error Analysis] Python does not allow the use of unassigned variables.
++ ++
>>> 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'
[Error Analysis] attribute errors are ultimately caused by immutable ancestor types, so there are no such methods.
++ ++
>>> 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
[Error Analysis] Empty ancestor and empty list, no index of 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
[Error Analysis] Generally, the Code indentation problem occurs.
++ ++
>>> f = file('1.txt')>>> f.readline()'AAAAA\n'>>> f.readline()'BBBBB\n'>>> f.next()'CCCCC\n'
[Error Analysis] If there is no line in the file, this exception will be reported.
>>> f.next() #Traceback (most recent call last):  File "<stdin>", line 1, in <module>StopIteration

The next method of an object that can be iterated will forward to the next result, and the StopIteration exception will be thrown at the end of a series of results.

++ ++

>>> string = 'SPAM'>>> a,b,c = stringTraceback (most recent call last):  File "<stdin>", line 1, in <module>ValueError: too many values to unpack
[Error Analysis] fewer variables are accepted. It should be
>>> A, B, c, d = string >>> a, d ('s', 'M') # Unless sliced >>> a, B, c = string [0], string [1], string [2:] >>> a, B, c ('s', 'P', 'am ') or >>> a, B, c = list (string [: 2]) + [string [2:] >>> a, B, c ('s ', 'P', 'am') or >>> (a, B), c = string [: 2], string [2:] >>> a, B, c ('s', 'P', 'am') or >>> (a, B), c) = ('SP ', 'am') >>> a, B, c ('s ', 'P', 'am') is simply: >>> 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'
[Error Analysis] This type of exception is triggered when the key mapped to the dictionary does not exist. Alternatively, this test can be performed.

>>> 'A' in mydic. keys () True >>> 'C' in mydic. keys () # Use in to test the ownership of members; False >>> D. get ('C', '"c" is not exist! ') # Use get or to get the key. If it does not exist, the error message' "c" is not exist will be printed! '
++ ++
  File "study.py", line 3    return None    ^IndentationError: unexpected indent
[Error Analysis] is generally caused by code indentation, which is caused by inconsistent tabs or space keys.

++ ++

>>> Def A (): return A () >>> A () # infinite loop. After all the memory resources are consumed, the maximum recursive depth error File "<pyshell #2>", line 2, in A return A () RuntimeError: maximum recursion depth exceededclass Bird: def _ init _ (self): self. hungry = True def eat (self): if self. hungry: print "Ahaha... "self. hungry = False else: print "No, Thanks! "This class defines the basic skills for birds to eat. If you are full, you will not eat any more. output result: >>> B = Bird () >>> B. eat () Ahaha...> b. eat () No, Thanks! The following subclass SingBird, class SingBird (Bird): def _ init _ (self): self. sound = 'squawk' def sing (self): print self. sound output result: >>> s = SingBird () >>> s. sing () squawkSingBird is a child of Bird, but if you call the eat () method of the Bird class, >>> 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'
[Error Analysis] The code error is clear. The initialization code in SingBird is overwritten, but there is no code to initialize hungry.
Class SingBird (Bird): def _ init _ (self): self. sound = 'squawk' self. hungry = Ture # Add 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
[Error Analysis] Add _ metaclass __= type in the first line of the module. I have not figured out why I should add
__metaclass__=typeclass 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] = 22TypeError: 'tuple' object does not support item assignment
[Error Analysis] The ancestor cannot be changed because it cannot be changed. It can be sliced or merged to achieve the goal.
>>> T = (1,2,3,4)>>> (22,) + T[1:](22, 2, 3, 4)
++ ++

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.