我们初学 Python 时很容易出现一些经典错误,想要弄懂 Python 的错误信息的含义也可能有点复杂,下面列出会让你的程序crash的17个常见运行时错误,并附以代码示例。
忘记在 if , elif , else , for , while , class , def 声明末尾添加符号:(导致“ SyntaxError :invalid syntax ”)
该类错误代码如下:
if spam == 42
print('Hello!')
2. 使用 = 而不是 ==(导致“ SyntaxError: invalid syntax ”)
= 是赋值操作符而 == 是“等于”比较操作符。
该类错误代码如下:
if spam = 42:
print('Hello!')
3. 错误的使用缩进量。(导致“ IndentationError:unexpected indent ”、“ IndentationError:unindent does not match any outer indetation level ”和“ IndentationError:expected an indented block ”)
记住,缩进增加只用在以: 结束的语句之后,在这之后必须恢复到之前的缩进格式。
该类错误代码如下:
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 ”)
通常你想迭代列表或字符串中数据项的索引,这需要调用 range() 函数。记得传递len(someList)的返回值,而非仅仅传递someList。
该类错误代码如下:
spam = ['cat', 'dog', 'mouse']
for i in range(spam):
print(spam[i])
5. 尝试去修改字符串的值。(导致“TypeError: 'str' object does not support item assignment”)
字符串是一种不可变的数据类型。该类错误发生时代码如下:
spam = 'I have a pet cat.'
spam[13] = 'r'
print(spam)
你实际想要这样:
spam = 'I have a pet cat.'
spam = spam[:13] + 'r' + spam[14:]
print(spam)
6. 尝试连接非字符串值和字符串值。(导致“TypeError: Can't convert 'int' object to str implicitly”)
该类错误发生时代码如下:
numEggs = 12
print('I have ' + numEggs + ' eggs.')
你实际上想要这样:
numEggs = 12
print('I have ' + str(numEggs) + ' eggs.')
或这样:
numEggs = 12
print('I have%seggs.' % (numEggs))
7. 在字符串首尾忘记添加引号。(导致“SyntaxError: EOL while scanning string literal”)
该类错误发生时代码如下:
print(Hello!')
或
print('Hello!)
或
myName = 'Al'
print('My name is ' + myName + . How are you?')
8. 变量或函数名拼写错误。(导致“NameError: name 'fooba' is not defined”)
该类错误发生时代码如下:
foobar = 'Al'
print('My name is ' + fooba)
或
spam = ruond(4.2)
或
spam = Round(4.2)
9. 方法名拼写错误。(导致“AttributeError: 'str' object has no attribute 'lowerr'”)
该类错误发生时代码如下:
spam = 'THIS IS IN LOWERCASE.'
spam = spam.lowerr()
10. 引用超过列表的最大索引。(导致“IndexError: list index out of range”)
该类错误发生时代码如下:
spam = ['cat', 'dog', 'mouse']
print(spam[6])
11. 使用不存在的字典键。(导致“KeyError: 'spam'”)
该类错误代码如下:
spam = {'cat': 'Zophie', 'dog': 'Basil', 'mouse': 'Whiskers'}
print('The name of my pet zebra is ' + spam['zebra'])
12. 尝试用Python关键字作为变量名。(导致“SyntaxError: invalid syntax”)
Python关键字(也叫保留字)不能用作变量名。
该类错误代码如下:
class = 'algebra'
Python 3的关键字有: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必须以一个有效值开头。
该类错误代码如下:
spam = 0
spam += 42
eggs += 42
14. 赋值局部变量前在函数中使用了局部变量(此时有与局部变量同名的全局变量存在)。(导致“UnboundLocalError: local variable 'foobar' referenced before assignment”)
在函数中使用与全局变量同名的局部变量相当复杂,规则是:如果已经为函数中的变量赋值,那么每当在函数中使用该变量时,它就是局部变量。否则,它就是函数中的全局变量。
因此,在没有为变量赋值前,不能在函数中将其用作全局变量。
该类错误代码如下:
someVar = 42
def myFunction():
print(someVar)
someVar = 100
myFunction()
15. 尝试用 range() 创建整数列表。(导致“TypeError: 'range' object does not support item assignment”)
有时你会想得到一个有序整数列表,range() 看起来似乎是个生成这种列表的不错方式。然而,你必须记住 range() 会返回“范围对象”,而不是一个实际的列表值。
该类错误代码如下:
spam = range(10)
spam[4] = -1
而你实际上想要这样:
spam = list(range(10))
spam[4] = -1
注意:这个 Python 2 中是可以的,因为 Python 2 的 range() 返回列表值。不过在 Python 3 中这么做就会出现上面的错误。
16. 没有++增量或--减量操作符。(导致“SyntaxError: invalid syntax”)
如果你以前是用的 C++,Java,PHP 这些语言,你可能会想用 ++ 或 -- 增减一个变量,但在 Python 中没有这样的操作。
该类错误代码如下:
spam = 0
spam++
而你实际上想这样:
spam = 0
spam += 1
17. 忘记将 self 添加为方法的第一个参数。(导致“TypeError: myMethod() takes no arguments (1 given)”)
该类错误代码如下:
class Foo():
def myMethod():
print('Hello!')
a = Foo()
a.myMethod()
你可能感兴趣:
你都用 Python 来做什么?www.zhihu.com
Python 的练手项目有哪些值得推荐?www.zhihu.com
官方微博:@景略集智
微信公众号:景略集智