From: http://www.cnblogs.com/smile-ls/archive/2013/05/20/3088393.html
When learning Python, it may be a bit complicated to understand the meaning of Python's error messages. Here are some common runtime errors that make your program crash.
1) Forget to add at the end of if, elif, else, for, while, class, def statements: (resulting in “SyntaxError: invalid syntax”)
The error will occur in code similar to the following:
if spam == 42
print (‘Hello!’)
2) Use = instead of == (resulting in "SyntaxError: invalid syntax")
= Is the assignment operator and == is equal to the comparison operation. The error occurs in the following code:
if spam = 42:
print (‘Hello!’)
3) Incorrect use of indentation. (Results in "IndentationError: unexpected indent", "IndentationError: unindent does not match any outer indetation level" and "IndentationError: expected an indented block")
Remember that the increase in indentation is only used after the statement that ends with: and must then revert to the previous indentation format. The error occurs in the following code:
print (‘Hello!’)
print (‘Howdy!’)
or:
if spam == 42:
print (‘Hello!’)
print (‘Howdy!’)
or:
if spam == 42:
print (‘Hello!’)
4) Forgot to call len () in the for loop statement (resulting in "TypeError:‘ list ’object cannot be interpreted as an integer")
Usually you want to iterate over the elements of a list or string by index, which requires calling the range () function. Remember to return the len value instead of returning this list.
The error occurs in the following code:
spam = [‘cat‘, ‘dog’, ‘mouse’]
for i in range (spam):
print (spam [i])
5) Try to modify the value of string (resulting in "TypeError:‘ str ’object does not support item assignment”)
string is an immutable data type, the error occurs in the following code:
spam = ‘I have a pet cat.’
spam [13] = ‘r’
print (spam)
And you actually want to do this:
spam = ‘I have a pet cat.’
spam = spam [: 13] + ‘r‘ + spam [14:]
print (spam)
6) Attempt to connect non-string values and strings (resulting in "TypeError: Ca n‘t convert‘ int ’object to str implicitly”)
The error occurs in the following code:
numEggs = 12
print (‘I have‘ + numEggs + ‘eggs.’)
And you actually want to do this:
numEggs = 12
print (‘I have‘ + str (numEggs) + ‘eggs.’)
or:
numEggs = 12
print (‘I have% s eggs.’% (numEggs))
7) Forget to add quotation marks at the beginning and end of the string (leading to "SyntaxError: EOL while scanning string literal")
The error occurs in the following code:
print (Hello! ‘)
or:
print (‘Hello!)
or:
myName = ‘Al’
print (‘My name is‘ + myName +. How are you? ’)
8) Misspelling of variable or function names (resulting in "NameError: name‘ fooba ’is not defined”)
The error occurs in the following code:
foobar = ‘Al’
print (‘My name is‘ + fooba)
or:
spam = ruond (4.2)
or:
spam = Round (4.2)
9) The spelling of the method name is incorrect (resulting in "AttributeError:‘ str ’object has no attribute‘ lowerr ’”)
The error occurs in the following code:
spam = ‘THIS IS IN LOWERCASE.’
spam = spam.lowerr ()
10) The reference exceeds the maximum index of the list (resulting in "IndexError: list index out of range")
The error occurs in the following code:
spam = [‘cat‘, ‘dog’, ‘mouse’]
print (spam [6])
11) Use a non-existent dictionary key (resulting in "KeyError: 'spam'")
The error occurs in the following code:
spam = {‘cat‘: ‘Zophie’, ‘dog’: ‘Basil’, ‘mouse’: ‘Whiskers’}
print (‘The name of my pet zebra is‘ + spam [‘zebra‘])
12) Try to use Python keywords as variable names (resulting in "SyntaxError: invalid syntax")
The Python key cannot be used as a variable name. This error occurs in the following code:
class = ‘algebra’
The keywords of Python3 are: and, as, assert, break, class, continue, def, del, elif, else, except, 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 defined new variable (resulting in "NameError: name‘ foobar ’is not defined")
Do not use 0 or an empty string as the initial value when declaring variables, so the sentence spam + = 1 using the increment operator is equal to spam = spam + 1, which means spam needs to specify a valid initial value.
The error occurs in the following code:
spam = 0
spam + = 42
eggs + = 42
14) Use local variables in the function before defining the local variables (at this time there is a global variable with the same name as the local variable) (leading to "UnboundLocalError: local variable‘ foobar ’referenced before assignment”)
It is very complicated to use the local variable in the function and the global variable with the same name exists at the same time. The rule of use is: if anything is defined in the function, if it is only used in the function, it is local, otherwise it is global variable.
This means that you cannot use it as a global variable in a function before defining it.
The error occurs in the following code:
someVar = 42
def myFunction ():
print (someVar)
someVar = 100
myFunction ()
15) Try to create a list of integers using range () (resulting in "TypeError:‘ range ’object does not support item assignment")
Sometimes you want to get an ordered list of integers, so range () looks like a good way to generate this list. However, you need to remember that range () returns "range object", not the actual list value.
The error occurs in the following code:
spam = range (10)
spam [4] = -1
Maybe this is what you want to do:
spam = list (range (10))
spam [4] = -1
(Note: spam = range (10) works in Python 2, because range () returns a list value in Python 2, but the above error occurs in Python 3)
16) Good in ++ or-increment and decrement operators. (Causes "SyntaxError: invalid syntax")
If you are used to other languages such as C ++, Java, PHP, etc., you may want to try to use ++ or-to increment and decrement a variable. There is no such operator in Python.
The error occurs in the following code:
spam = 1
spam ++
Maybe this is what you want to do:
spam = 1
spam + = 1
17) Forgot to add self parameter to the first parameter of the method (resulting in "TypeError: myMethod () takes no arguments (1 given)")
The error occurs in the following code:
class Foo ():
def myMethod ():
print (‘Hello!’)
a = Foo ()
a.myMethod ()
[Reprinted] 17 common Python runtime errors for newbies
Tags: expec cannot als arch blog ber smi parameter dex
Original address: http://www.cnblogs.com/YangtzeYu/p/7857527.html