17個新手常見Python運行時錯誤


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!')

  

譯者信息

當初學 Python 時,想要弄懂 Python 的錯誤信息的含義可能有點復雜。這里列出了常見的的一些讓你程序 crash 的運行時錯誤。 

1)忘記在 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) 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 therange() function. Just remember to pass the return value of len(someList), instead of passing justsomeList. 

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.) 

 

譯者信息

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”) 

通常你想要通過索引來迭代一個list或者string的元素,這需要調用 range() 函數。要記得返回len 值而不是返回這個列表。 

該錯誤發生在如下代碼中: 

spam = ['cat', 'dog', 'mouse']
for i in range(spam):
    print(spam[i])
  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?')

 

譯者信息

5)嘗試修改string的值(導致“TypeError: 'str' object does not support item assignment”) 

string是一種不可變的數據類型,該錯誤發生在如下代碼中: 

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 %s eggs.' % (numEggs))

7)在字符串首尾忘記加引號(導致“SyntaxError: EOL while scanning string literal”) 

該錯誤發生在如下代碼中: 

print(Hello!')

或者:

print('Hello!)

或者:

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'])

 

譯者信息

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)引用超過list最大索引(導致“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) 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()

 

譯者信息

12)嘗試使用Python關鍵字作為變量名(導致“SyntaxError:invalid syntax”) 

Python關鍵不能用作變量名,該錯誤發生在如下代碼中: 

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需要指定一個有效的初始值。 

該錯誤發生在如下代碼中: 

spam = 0
spam += 42
eggs += 42

14)在定義局部變量前在函數中使用局部變量(此時有與局部變量同名的全局變量存在)(導致“UnboundLocalError: local variable 'foobar' referenced before assignment”) 

在函數中使用局部變來那個而同時又存在同名全局變量時是很復雜的,使用規則是:如果在函數中定義了任何東西,如果它只是在函數中使用那它就是局部的,反之就是全局變量。 

這意味着你不能在定義它之前把它當全局變量在函數中使用。 

該錯誤發生在如下代碼中: 

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()
譯者信息

15)嘗試使用 range()創建整數列表(導致“TypeError: 'range' object does not support item assignment”) 

有時你想要得到一個有序的整數列表,所以 range() 看上去是生成此列表的不錯方式。然而,你需要記住 range() 返回的是 “range object”,而不是實際的 list 值。 

該錯誤發生在如下代碼中: 

spam = range(10)
spam[4] = -1

也許這才是你想做: 

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中是沒有這樣的操作符的。 

該錯誤發生在如下代碼中: 

spam = 1
spam++

也許這才是你想做的: 

spam = 1
spam += 1

17)忘記為方法的第一個參數添加self參數(導致“TypeError: myMethod() takes no arguments (1 given)”) 

該錯誤發生在如下代碼中: 

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM