新手必看,17個常見的Python運行時錯誤
(給機器學(xué)習(xí)算法與Python實戰(zhàn)加星標,提升AI技能)
作者:Al Sweigart 翻譯:彭博??來源:開源中國?
https://www.oschina.net/question/89964_62779?
英文原文:https://inventwithpython.com/blog/2012/07/09/16-common-python-runtime-errors-beginners-find/
初入門的 Pythoner 在運行代碼時免不了會遇到一些錯誤,剛開始可能看起來比較費勁。
隨著代碼量的積累,熟能生巧,當遇到一些運行時錯誤時能夠很快的定位問題原題。
下面整理了常見的 17 個錯誤,希望能夠幫助到大家。
1、忘記在 if,for,def,elif,else,class 等聲明末尾加 :會導(dǎo)致SyntaxError :invalid syntax如下:
if?spam?==?42
??print( Hello! )
2、使用= 而不是 ==也會導(dǎo)致SyntaxError: invalid syntax
= 是賦值操作符,而 == 是等于比較操作
該錯誤發(fā)生在如下代碼中:
if?spam?=?42:
???print( Hello! )
3、錯誤的使用縮進量導(dǎo)致
IndentationError:unexpected indent
IndentationError:unindent does not match any outer indetation level
以及IndentationError:expected an indented block
記住縮進增加只用在以:結(jié)束的語句之后,而之后必須恢復(fù)到之前的縮進格式。
該錯誤發(fā)生在如下代碼中:
print( Hello! )
???print( Howdy! )
或者:
if?spam?==?42:
????print( Hello! )
print( Howdy! )
4、在 for 循環(huán)語句中忘記調(diào)用 len()
導(dǎo)致TypeError: list object cannot be interpreted as an integer
通常你想要通過索引來迭代一個 list 或者 string 的元素,這需要調(diào)用 range() 函數(shù)。
要記得返回 len 值而不是返回這個列表。
該錯誤發(fā)生在如下代碼中:
spam?=?[ cat ,? dog ,? mouse ]
for?i?in?range(spam):
????print(spam[i])5、嘗試修改 string 的值
導(dǎo)致TypeError: str object does not support item assignment
string 是一種不可變的數(shù)據(jù)類型,該錯誤發(fā)生在如下代碼中:
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、嘗試連接非字符串值與字符串
導(dǎo)致 TypeError: Can t convert int object to str implicitly
該錯誤發(fā)生在如下代碼中:
numEggs?=?12
print( I?have? ?+?numEggs?+? ?eggs. )
而正確做法是:
numEggs?=?12
print( I?have? ?+?str(numEggs)?+? ?eggs. )
numEggs?=?12
print( I?have?%s?eggs. ?%?(numEggs))
7、在字符串首尾忘記加引號
導(dǎo)致SyntaxError: EOL while scanning string literal
該錯誤發(fā)生在如下代碼中:
print(Hello! )
print( Hello!)
myName?=? Al
print( My?name?is? ?+?myName?+?.?How?are?you? )
8、變量或者函數(shù)名拼寫錯誤
導(dǎo)致NameError: name fooba is not defined
該錯誤發(fā)生在如下代碼中:
foobar?=? Al
print( My?name?is? ?+?fooba)
spam?=?ruond(4.2)
spam?=?Round(4.2)
9、方法名拼寫錯誤
導(dǎo)致 AttributeError: str object has no attribute lowerr
該錯誤發(fā)生在如下代碼中:
spam?=? THIS?IS?IN?LOWERCASE.
spam?=?spam.lowerr()
10、引用超過 list 最大索引
導(dǎo)致 IndexError: list index out of range
該錯誤發(fā)生在如下代碼中:
spam?=?[ cat ,? dog ,? mouse ]
print(spam[6])
11、使用不存在的字典鍵值
導(dǎo)致KeyError:‘spam’
該錯誤發(fā)生在如下代碼中:
spam?=?{ cat :? Zophie ,? dog :? Basil ,? mouse :? Whiskers }
print( The?name?of?my?pet?zebra?is? ?+?spam[ zebra ])
12、嘗試使用 Python 關(guān)鍵字作為變量名
導(dǎo)致SyntaxError:invalid syntax
Python 關(guān)鍵不能用作變量名,該錯誤發(fā)生在如下代碼中:
class?=? algebra
Python3 的關(guān)鍵字有:
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、在一個定義新變量中使用增值操作符
導(dǎo)致NameError: name foobar is not defined
不要在聲明變量時使用 0 或者空字符串作為初始值,這樣使用自增操作符的一句spam += 1等于spam = spam + 1,這意味著 spam 需要指定一個有效的初始值。
該錯誤發(fā)生在如下代碼中:
spam?=?0
spam?+=?42
eggs?+=?42
14、在定義局部變量前在函數(shù)中使用局部變量(此時有與局部變量同名的全局變量存在)
導(dǎo)致UnboundLocalError: local variable foobar referenced before assignment
在函數(shù)中使用局部變量而同時又存在同名全局變量時是很復(fù)雜的,使用規(guī)則是:
如果在函數(shù)中定義了任何東西,如果它只是在函數(shù)中使用那它就是局部的,反之就是全局變量。
這意味著你不能在定義它之前把它當全局變量在函數(shù)中使用。
該錯誤發(fā)生在如下代碼中:
someVar?=?42
def?myFunction():
????print(someVar)
????someVar?=?100
myFunction()
15、嘗試使用 range()創(chuàng)建整數(shù)列表
導(dǎo)致TypeError: range object does not support item assignment
有時你想要得到一個有序的整數(shù)列表,所以 range() 看上去是生成此列表的不錯方式。然而,你需要記住 range()返回的是 range object,而不是實際的 list 值。
該錯誤發(fā)生在如下代碼中:
spam?=?range(10)
spam[4]?=?-1
正確寫法:
spam?=?list(range(10))
spam[4]?=?-1
注意:在 Python 2 中 spam = range(10)是能行的,因為在 Python 2 中 range()返回的是list值,但是在 Python 3 中就會產(chǎn)生以上錯誤.
16、不存在 ++ 或者 -- 自增自減操作符
導(dǎo)致SyntaxError: invalid syntax
如果你習(xí)慣于例如 C++ , Java , PHP 等其他的語言,也許你會想要嘗試使用++ 或者 -- 自增自減一個變量。
在 Python 中是沒有這樣的操作符的。
該錯誤發(fā)生在如下代碼中:
spam?=?1
spam++
正確寫法:
spam?=?1
spam?+=?1
17、忘記為方法的第一個參數(shù)添加 self 參數(shù)
導(dǎo)致TypeError: myMethod() takes no arguments (1 given)
該錯誤發(fā)生在如下代碼中:
class?Foo():
????def?myMethod():
????????print( Hello! )
a?=?Foo()
a.myMethod()推薦閱讀
(點擊標題可跳轉(zhuǎn)閱讀)
深度學(xué)習(xí)調(diào)參技巧的總結(jié)
學(xué)深度學(xué)習(xí)是不是需要先學(xué)機器學(xué)習(xí)? 臥槽,我學(xué)會了用Python預(yù)測股票價格
老鐵,三連支持一下,好嗎?↓↓↓
