17 common Python runtime errors for beginners, 17 python

Source: Internet
Author: User

[Switch] 17 common Python runtime errors for beginners, 17 python

Original address: http://www.oschina.net/question/89964_62779? P = 1

 

When I first learned Python, it may be a bit complicated to understand the meaning of the Python error message. Some common running errors that make your program crash appear here.

1) forget to add (resulting in "SyntaxError: invalid syntax") at the end of the if, elif, else, for, while, class, and def declaration ")

This error will occur in code similar to the following:

? 12 if spam = 42 print ('Hello! ')
2) use = instead of = (resulting in "SyntaxError: invalid syntax ")

= Is the value assignment operator and = is a comparison operation. This error occurs in the following code:

? 12 if spam = 42: print ('Hello! ')
3) The number of indentions is incorrect. (Resulting in "IndentationError: unexpected indent", "IndentationError: unindent does not match any outer indetation level", and "IndentationError: expected an indented block ")

Remember to add indentation only after the statement ending with:, and then it must be restored to the original indent format. This error occurs in the following code:

? 12345678910111213 print ('Hello! ') Print ('Howdy! ') Or: if spam = 42: print ('Hello! ') Print ('Howdy! ') Or: if spam = 42: print ('Hello! ')
4) forget to call len () in the for loop Statement (resulting in "TypeError: 'LIST' object cannot be interpreted as an integer ")

Generally, You Want To iterate a list or string element through an index. You need to call the range () function. Remember to return the len value instead of the list.

This error occurs in the following code:

? 123 spam = ['cat', 'dog ', 'mouse'] for I in range (spam): print (spam [I])
5) try to modify the string value (resulting in "TypeError: 'str' object does not support item assignment ")

String is an unchangeable data type. This error occurs in the following code:

? 123 spam = 'I have a pet cat.' spam [13] = 'R' print (spam)
But you actually want to do this:

? 123 spam = 'I have a pet cat.' spam = spam [: 13] + 'R' + spam [14:] print (spam)
6) try to connect a non-string value with a string (resulting in "TypeError: Can't convert 'int' object to str implicitly ")

This error occurs in the following code:

? 12 numEggs = 12 print ('I have' + numEggs + 'eggs .')

But you actually want to do this:

? 1234567 numEggs = 12 print ('I have' + str (numEggs) + 'eggs. ') or: numEggs = 12 print (' I have % s eggs. '% (numEggs ))
7) add quotation marks at the beginning and end of the string (resulting in "SyntaxError: EOL while scanning string literal ")

This error occurs in the following code:


? 12345678910 print (Hello! ') Or: print ('Hello !) Or: myName = 'al' print ('My name is '+ myName +. How are you? ')
8) misspelling of variables or function names (resulting in "NameError: name 'fooba' is not defined ")

This error occurs in the following code:

? 12345678910 foobar = 'al' print ('My name is '+ fooba) or: spam = ruond (4.2) or: spam = Round (4.2)
9) incorrect method name spelling (resulting in "AttributeError: 'str' object has no attribute 'lowerr '")

This error occurs in the following code:

? 12 spam = 'this is in lowercase. 'spam = spam. lowerr ()
10) Reference exceeds the maximum list index (resulting in "IndexError: list index out of range ")

This error occurs in the following code:

? 12 spam = ['cat', 'dog ', 'mouse'] print (spam [6])
11) use a non-existent dictionary key value (resulting in "KeyError: 'spam '")

This error occurs in the following code:

? 12 spam = {'cat': 'zophie ', 'dog': 'basil ', 'mouse ': 'whiskers'} print ('the name of my pet zebra is '+ spam ['zebra'])
12) try to use the Python keyword as the variable name (resulting in "SyntaxError: invalid syntax ")

The key to Python cannot be used as a variable name. This error occurs in the following code:

? 1 class = 'algebr'
Python3 keywords include: and, as, assert, break, class, continue, def, del, elif, else, else t, False, finally, for, from, global, if, import, in, is, lambda, None, nonlocal, not, or, pass, raise, return, True, try, while, with, yield

13) use the value-added operator in a new variable definition (resulting in "NameError: name'foobar' is not defined ")

Do not use 0 or an empty string as the initial value when declaring a variable. In this way, the use of the auto-increment operator spam + = 1 equals spam = spam + 1, this means that spam needs to specify a valid initial value.

This error occurs in the following code:

? 123 spam = 0 spam + = 42 eggs + = 42
14) use a local variable in the function before defining the local variable (a global variable with the same name as the local variable exists) (resulting in "UnboundLocalError: local variable 'foobar' referenced before assignment ")

It is very complicated to use local variables in a function and there are global variables with the same name at the same time. The rule is as follows: if a function defines anything, if it is used only in functions, it is local, and vice versa.

This means that you cannot use it as a global variable in the function before defining it.

This error occurs in the following code:

? 12345 someVar = 42 def myFunction (): print (someVar) someVar = 100 myFunction ()
15) Try to use range () to create an integer list (resulting in "TypeError: 'range' object does not support item assignment ")

Sometimes you want to get an ordered integer list, so range () seems to be a good way to generate this list. However, you need to remember that range () returns "range object" instead of the actual list value.

This error occurs in the following code:

? 12 spam = range (10) spam [4] =-1
Maybe this is what you want to do:

? 12 spam = list (range (10) spam [4] =-1
(Note: In Python 2, spam = range (10) can work, because range () in Python 2 returns the list value, but the above errors will occur in Python 3)

16) Not bad in ++ or -- auto-incrementing auto-subtraction operator. (Cause "SyntaxError: invalid syntax ")

If you are used to other languages such as C ++, Java, and PHP, you may want to use ++ or -- auto-increment to subtract a variable. There is no such operator in Python.

This error occurs in the following code:

? 12 spam = 1 spam ++
Maybe this is what you want to do:

? 12 spam = 1 spam + = 1
17) forgot to add the self parameter to the first parameter of the method (resulting in "TypeError: myMethod () takes no arguments (1 given )")

This error occurs in the following code:

? 12345 class Foo (): def myMethod (): print ('Hello! ') A = Foo () a. myMethod ()

 

Related Article

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.