@1007477689
2020-07-20T12:00:16.000000Z
字数 6525
阅读 743
Python
英文原文:
https://inventwithpython.com/blog/2012/07/09/16-common-python-runtime-errors-beginners-find/
初入门的 Pythoner 在运行代码时免不了会遇到一些错误,刚开始可能看起来比较费劲。
随着代码量的积累,熟能生巧,当遇到一些运行时错误时能够很快的定位问题原题。
下面整理了常见的 个错误,希望能够帮助到大家。
忘记在 if,for,def,elif,else,class 等声明末尾加 :会导致 SyntaxError :
1) Forgetting to put a ":" at the end of an if, elif, else, for, while, class, or def statement. (Causes “SyntaxError: invalid syntax”)
invalid syntax 如下:
This error happens with code like this:
if spam == 42print('Hello!')
使用 = 而不是 == 也会导致 SyntaxError: invalid syntax
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.
IndentationError:unexpected indent
IndentationError:unindent does not match any outer indetation level
以及IndentationError:expected an indented block
记住缩进增加只用在以:结束的语句之后,而之后必须恢复到之前的缩进格式。
该错误发生在如下代码中:
This error happens with code like this:
print('Hello!')print('Howdy!')
或者:
if spam == 42:print('Hello!')print('Howdy!')
在 for 循环语句中忘记调用 len()导致 TypeError: 'list' object cannot be interpreted as an integer
4) Forgetting the len() call in a for loop statement. (Causes “TypeError: 'list' object cannot be interpreted as an integer”)
通常你想要通过索引来迭代一个 list 或者 string 的元素,这需要调用 range() 函数。要记得返回 len 值而不是返回这个列表。
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])
尝试修改 string 的值,导致 TypeError: 'str' object does not support item assignment
5) Trying to modify a string value. (Causes “TypeError: 'str' object does not support item assignment”)
string 是一种不可变的数据类型,该错误发生在如下代码中:
Strings are an immutable data type. This error happens with code like this:
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)
尝试连接非字符串值与字符串(导致 TypeError: Can't convert 'int' object to str implicitly)
6) Trying to concatenate a non-string value to a string value. (Causes “TypeError: Cannot convert 'int' object to str implicitly”)
该错误发生在如下代码中:
This error happens with code like this:
numEggs = 12print('I have ' + numEggs + ' eggs.')
而正确做法是:
numEggs = 12print('I have ' + str(numEggs) + ' eggs.')
numEggs = 12print('I have %s eggs.' % (numEggs))
在字符串首尾忘记加引号(导致 SyntaxError: EOL while scanning string literal)
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!')print('Hello!)myName = 'Al'print('My name is ' + myName + . How are you?')
变量或者函数名拼写错误(导致 NameError: name 'fooba' is not defined)
8) A type 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)spam = ruond(4.2)spam = Round(4.2)
方法名拼写错误(导致 AttributeError: 'str' object has no attribute 'lowerr')
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()
引用超过 list 最大索引(导致 IndexError: list index out of range)
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])
使用不存在的字典键值(导致 KeyError:‘spam’)
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'])
尝试使用 Python 关键字作为变量名(导致 SyntaxError:invalid syntax)
12) Trying to use a Python keyword for a variable name. (Causes “SyntaxError: invalid syntax”)
Python 关键不能用作变量名,该错误发生在如下代码中:
The Python keywords (also called reserved words) cannot be used for variable names. This happens with code like:
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
在一个定义新变量中使用增值操作符
导致NameError: name 'foobar' is not defined
不要在声明变量时使用 0 或者空字符串作为初始值,这样使用自增操作符的一句spam += 1等于spam = spam + 1,这意味着 spam 需要指定一个有效的初始值。
该错误发生在如下代码中:
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.
导致UnboundLocalError: local variable 'foobar' referenced before assignment
在函数中使用局部变量而同时又存在同名全局变量时是很复杂的,使用规则是:
如果在函数中定义了任何东西,如果它只是在函数中使用那它就是局部的,反之就是全局变量。
这意味着你不能在定义它之前把它当全局变量在函数中使用。
该错误发生在如下代码中:
This error happens with code like this:
someVar = 42def myFunction():print(someVar)someVar = 100myFunction()
尝试使用 range() 创建整数列表,导致TypeError: 'range' object does not support item assignment
15) Trying to use range() to create a list of integers. (Causes “TypeError: 'range' object does not support item assignment”)
有时你想要得到一个有序的整数列表,所以 range() 看上去是生成此列表的不错方式。然而,你需要记住 range() 返回的是 range object,而不是实际的 list 值。
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
正确写法:
spam = list(range(10))spam[4] = -1
注意:在 Python 2 中 spam = range(10) 是能行的,因为在 Python 2 中 range() 返回的是 list 值,但是在 Python 3 中就会产生以上错误.
不存在 ++ 或者 -- 自增自减操作符,导致SyntaxError: invalid syntax
16) There is no ++ increment or –- decrement operator. (Causes “SyntaxError: invalid syntax”)
如果你习惯于例如 C++ , Java , PHP 等其他的语言,也许你会想要尝试使用++ 或者 -- 自增自减一个变量。在 Python 中是没有这样的操作符的。
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 = 1spam++
正确写法:
spam = 1spam += 1
忘记为方法的第一个参数添加 self 参数(导致 TypeError: myMethod() takes no arguments (1 given))
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()