17个新手常见Python运行时错误
当初学 Python 时,想要弄懂 Python 的错误信息的含义可能有点复杂。这里列出了常见的的一些让你程序 crash 的运行时错误。
1)忘记在 if , elif , else , for , while , class ,def 声明末尾添加 :(导致 “SyntaxError :invalid syntax”)
该错误将发生在类似如下代码中:
1
2
|
if spam = = 42 print ( 'Hello!' ) |
2)使用 = 而不是 ==(导致“SyntaxError: invalid syntax”)
= 是赋值操作符而 == 是等于比较操作。该错误发生在如下代码中:
1
2
|
if spam = 42 : print ( 'Hello!' ) |
3)错误的使用缩进量。(导致“IndentationError:unexpected indent”、“IndentationError:unindent does not match any outer indetation level”以及“IndentationError:expected an indented block”)
记住缩进增加只用在以:结束的语句之后,而之后必须恢复到之前的缩进格式。该错误发生在如下代码中:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
print ( 'Hello!' ) print ( 'Howdy!' ) 或者: if spam = = 42 : print ( 'Hello!' ) print ( 'Howdy!' ) 或者: if spam = = 42 : print ( 'Hello!' ) |
4)在 for 循环语句中忘记调用 len() (导致“TypeError: 'list' object cannot be interpreted as an integer”)
通常你想要通过索引来迭代一个list或者string的元素,这需要调用 range() 函数。要记得返回len 值而不是返回这个列表。
该错误发生在如下代码中:
1
2
3
|
spam = [ 'cat' , 'dog' , 'mouse' ] for i in range (spam): print (spam[i]) |
5)尝试修改string的值(导致“TypeError: 'str' object does not support item assignment”)
string是一种不可变的数据类型,该错误发生在如下代码中:
1
2
3
|
spam = 'I have a pet cat.' spam[ 13 ] = 'r' print (spam) |
而你实际想要这样做:
1
2
3
|
spam = 'I have a pet cat.' spam = spam[: 13 ] + 'r' + spam[ 14 :] print (spam) |
6)尝试连接非字符串值与字符串(导致 “TypeError: Can't convert 'int' object to str implicitly”)
该错误发生在如下代码中:
1
2
|
numEggs = 12 print ( 'I have ' + numEggs + ' eggs.' ) |
而你实际想要这样做:
1
2
3
4
5
6
7
|
numEggs = 12 print ( 'I have ' + str (numEggs) + ' eggs.' ) 或者: numEggs = 12 print ( 'I have %s eggs.' % (numEggs)) |
7)在字符串首尾忘记加引号(导致“SyntaxError: EOL while scanning string literal”)
该错误发生在如下代码中:
1
2
3
4
5
6
7
8
9
10
|
print (Hello!') 或者: print ('Hello!) 或者: myName = 'Al' print ( 'My name is ' + myName + . How are you?') |
8)变量或者函数名拼写错误(导致“NameError: name 'fooba' is not defined”)
该错误发生在如下代码中:
1
2
3
4
5
6
7
8
9
10
|
foobar = 'Al' print ( 'My name is ' + fooba) 或者: spam = ruond( 4.2 ) 或者: spam = Round ( 4.2 ) |
9)方法名拼写错误(导致 “AttributeError: 'str' object has no attribute 'lowerr'”)
该错误发生在如下代码中:
1
2
|
spam = 'THIS IS IN LOWERCASE.' spam = spam.lowerr() |
10)引用超过list最大索引(导致“IndexError: list index out of range”)
该错误发生在如下代码中:
1
2
|
spam = [ 'cat' , 'dog' , 'mouse' ] print (spam[ 6 ]) |
11)使用不存在的字典键值(导致“KeyError:‘spam’”)
该错误发生在如下代码中:
1
2
|
spam = { 'cat' : 'Zophie' , 'dog' : 'Basil' , 'mouse' : 'Whiskers' } print ( 'The name of my pet zebra is ' + spam[ 'zebra' ]) |
12)尝试使用Python关键字作为变量名(导致“SyntaxError:invalid syntax”)
Python关键不能用作变量名,该错误发生在如下代码中:
1
|
class = 'algebra' |
Python3的关键字有: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)在一个定义新变量中使用增值操作符(导致“NameError: name 'foobar' is not defined”)
不要在声明变量时使用0或者空字符串作为初始值,这样使用自增操作符的一句spam += 1等于spam = spam + 1,这意味着spam需要指定一个有效的初始值。
该错误发生在如下代码中:
1
2
3
|
spam = 0 spam + = 42 eggs + = 42 |
14)在定义局部变量前在函数中使用局部变量(此时有与局部变量同名的全局变量存在)(导致“UnboundLocalError: local variable 'foobar' referenced before assignment”)
在函数中使用局部变来那个而同时又存在同名全局变量时是很复杂的,使用规则是:如果在函数中定义了任何东西,如果它只是在函数中使用那它就是局部的,反之就是全局变量。
这意味着你不能在定义它之前把它当全局变量在函数中使用。
该错误发生在如下代码中:
1
2
3
4
5
|
someVar = 42 def myFunction(): print (someVar) someVar = 100 myFunction() |
15)尝试使用 range()创建整数列表(导致“TypeError: 'range' object does not support item assignment”)
有时你想要得到一个有序的整数列表,所以 range() 看上去是生成此列表的不错方式。然而,你需要记住 range() 返回的是 “range object”,而不是实际的 list 值。
该错误发生在如下代码中:
1
2
|
spam = range ( 10 ) spam[ 4 ] = - 1 |
也许这才是你想做:
1
2
|
spam = list ( range ( 10 )) spam[ 4 ] = - 1 |
(注意:在 Python 2 中 spam = range(10) 是能行的,因为在 Python 2 中 range() 返回的是list值,但是在 Python 3 中就会产生以上错误)
16)不错在 ++ 或者 -- 自增自减操作符。(导致“SyntaxError: invalid syntax”)
如果你习惯于例如 C++ , Java , PHP 等其他的语言,也许你会想要尝试使用 ++ 或者 -- 自增自减一个变量。在Python中是没有这样的操作符的。
该错误发生在如下代码中:
1
2
|
spam = 1 spam + + |
也许这才是你想做的:
1
2
|
spam = 1 spam + = 1 |
17)忘记为方法的第一个参数添加self参数(导致“TypeError: myMethod() takes no arguments (1 given)”)
该错误发生在如下代码中:
1
2
3
4
5
|
class Foo(): def myMethod(): print ( 'Hello!' ) a = Foo() a.myMethod() |
没有看的原文
Figuring out what Python's error messages mean can be kind of tricky when you are first learning the language. Here's a list of common errors that result in runtime error messages which will crash your program.
1) Forgetting to put a : at the end of an if
, elif
, else
, for
, while
, class
, or def
statement. (Causes “SyntaxError: invalid syntax
”)
This error happens with code like this:
if spam == 42 print('Hello!')
2) Using =
instead of ==
. (Causes “SyntaxError: invalid syntax
”)
The =
is the assignment operator while ==
is the "is equal to" comparison operator. This error happens with code like this:
if spam = 42: print('Hello!')
3) Using the wrong amount of indentation. (Causes “IndentationError: unexpected indent
” and “IndentationError: unindent does not match any outer indentation level
” and “IndentationError: expected an indented block
”)
Remember that the indentation only increases after a statement ending with a :
colon, and afterwards must return to the previous indentation. This error happens with code like this:
print('Hello!') print('Howdy!')
...and this:
if spam == 42: print('Hello!') print('Howdy!')
...and this:
if spam == 42: print('Hello!')
4) Forgetting the len()
call in a for
loop statement. (Causes “TypeError: 'list' object cannot be interpreted as an integer
”)
Commonly you want to iterate over the indexes of items in a list or string, which requires calling the range()
function. Just remember to pass the return value of len(someList)
, instead of passing just someList
.
This error happens with code like this:
spam = ['cat', 'dog', 'mouse'] for i in range(spam): print(spam[i])
(Update: As a few have pointed out, what you might need is just for i in spam:
rather than the above code. But the above is for the very legitimate case where you need the index in the body of the loop, rather than just the value itself.)
5) Trying to modify a string value. (Causes “TypeError: 'str' object does not support item assignment
”)
Strings are an immutable data type. This error happens with code like this:
spam = 'I have a pet cat.' spam[13] = 'r' print(spam)
What you probably want is this:
spam = 'I have a pet cat.' spam = spam[:13] + 'r' + spam[14:] print(spam)
6) Trying to concatenate a non-string value to a string value. (Causes “TypeError: Can't convert 'int' object to str implicitly
”)
This error happens with code like this:
numEggs = 12 print('I have ' + numEggs + ' eggs.')
What you want to do is this:
numEggs = 12 print('I have ' + str(numEggs) + ' eggs.')
...or this:
numEggs = 12 print('I have %s eggs.' % (numEggs))
7) Forgetting a quote to begin or end a string value. (Causes “SyntaxError: EOL while scanning string literal
”)
This error happens with code like this:
print(Hello!')
...or this:
print('Hello!)
...or this:
myName = 'Al' print('My name is ' + myName + . How are you?')
8) A typo for a variable or function name. (Causes “NameError: name 'fooba' is not defined
”)
This error happens with code like this:
foobar = 'Al' print('My name is ' + fooba)
...or this:
spam = ruond(4.2)
...or this:
spam = Round(4.2)
9) A typo for a method name. (Causes “AttributeError: 'str' object has no attribute 'lowerr'
”)
This error happens with code like this:
spam = 'THIS IS IN LOWERCASE.' spam = spam.lowerr()
10) Going past the last index of a list. (Causes “IndexError: list index out of range
”)
This error happens with code like this:
spam = ['cat', 'dog', 'mouse'] print(spam[6])
11) Using a non-existent dictionary key. (Causes “KeyError: 'spam'
”)
This error happens with code like this:
spam = {'cat': 'Zophie', 'dog': 'Basil', 'mouse': 'Whiskers'} print('The name of my pet zebra is ' + spam['zebra'])
12) Trying to use a Python keyword for a variable name. (Causes “SyntaxError: invalid syntax
”)
The Python keywords (also called reserved words) cannot be used for variable names. This happens with code like:
class = 'algebra'
The Python 3 keywords 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) Using an augmented assignment operator on a new variable. (Causes “NameError: name 'foobar' is not defined
”)
Do not assume that variables start off with a value such as 0
or the blank string. A statement with an augmented operator like spam += 1
is equivalent to spam = spam + 1
. This means that there must be a value in spam
to begin with.
This error happens with code like this:
spam = 0 spam += 42 eggs += 42
14) Using a local variable (with the same name as a global variable) in a function before assigning the local variable. (Causes “UnboundLocalError: local variable 'foobar' referenced before assignment
”)
Using a local variable in a function that has the same name as a global variable is tricky. The rule is: if a variable in a function is ever assigned something, it is always a local variable when used inside that function. Otherwise, it is the global variable inside that function.
This means you cannot use it as a global variable in the function before assigning it.
This error happens with code like this:
someVar = 42 def myFunction(): print(someVar) someVar = 100 myFunction()
15) Trying to use range()
to create a list of integers. (Causes “TypeError: 'range' object does not support item assignment
”)
Sometimes you want a list of integer values in order, so range()
seems like a good way to generate this list. However, you must remember that range()
returns a "range object", and not an actual list value.
This error happens with code like this:
spam = range(10) spam[4] = -1
What you probably want to do is this:
spam = list(range(10)) spam[4] = -1
(Update: This works in Python 2, because Python 2's range()
does return a list value. However, trying to do this in Python 3 will result in the above error.)
16) There is no ++
increment or –-
decrement operator. (Causes “SyntaxError: invalid syntax
”)
If you come from a different programming language like C++, Java, or PHP, you may try to increment or decrement a variable with ++
or --
. There are no such operators in Python.
This error happens with code like this:
spam = 0 spam++
What you want to do is this:
spam = 0 spam += 1
17) Update: As Luciano points out in the comments, it is also common to forget adding self
as the first parameter for a method. (Causes “TypeError: myMethod() takes no arguments (1 given)
”)
This error happens with code like this:
class Foo(): def myMethod(): print('Hello!') a = Foo() a.myMethod()
A short explanation of various error messages appears in Appendix D of the "Invent with Python" book.