對於新手,初學Python時,總會遇到這樣那樣的報錯,想要弄懂Python錯誤信息的含義可能還不知道怎麼做,這裡列出了一些比較常見的Python報錯問題,希望對於學習Python的人能夠有些幫助。
1)嘗試連接非字符串值與字符串(導致 「TypeError: Can’t convert 『int』 object to str implicitly」)
該錯誤發生在如下代碼中:
numEggs = 12print('I have ' + numEggs + ' eggs.')
而你實際想要這樣做:
numEggs = 12print('I have ' + str(numEggs) + ' eggs.')或者:numEggs = 12print('I have %s eggs.' % (numEggs))
2)在字符串首尾忘記加引號(導致「SyntaxError: EOL while scanning string literal」)
該錯誤發生在如下代碼中:
print(Hello!')或者:print('Hello!)或者:myName = 'Al'print('My name is ' + myName + . How are you?')
3)變量或者函數名拼寫錯誤(導致「NameError: name 『fooba』 is not defined」)
該錯誤發生在如下代碼中:
foobar = 'Al'print('My name is ' + fooba)或者:spam = ruond(4.2)或者:spam = Round(4.2)
4)方法名拼寫錯誤(導致 「AttributeError: 『str』 object has no attribute 『lowerr『」)
該錯誤發生在如下代碼中:
spam = 'THIS IS IN LOWERCASE.'spam = spam.lowerr()
5)引用超過list最大索引(導致「IndexError: list index out of range」)
該錯誤發生在如下代碼中:
spam = ['cat', 'dog', 'mouse']print(spam[6])
6)使用不存在的字典鍵值(導致「KeyError:『spam』」)
該錯誤發生在如下代碼中:
spam = {'cat': 'Zophie', 'dog': 'Basil', 'mouse': 'Whiskers'}print('The name of my pet zebra is ' + spam['zebra'])
7)忘記在 if, elif , else , for , while , class ,def 聲明末尾添加 :(導致 「SyntaxError :invalid syntax」)
該錯誤將發生在類似如下代碼中:
if spam == 42print('Hello!')
8)使用 = 而不是 ==(導致「SyntaxError: invalid syntax」)
= 是賦值操作符而 == 是等於比較操作。該錯誤發生在如下代碼中:
if spam = 42:print('Hello!')
9)使用錯誤的縮進量。(導致「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!')
10)在 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])
python一些最重要的內建異常類名總結
AttributeError:屬性錯誤,特性引用和賦值失敗時會引發屬性錯誤
NameError:試圖訪問的變量名不存在
SyntaxError:語法錯誤,代碼形式錯誤
Exception:所有異常的基類,因為所有python異常類都是基類Exception的其中一員,異常都是從基類Exception繼承的,並且都在exceptions模塊中定義。
IOError:一般常見於打開不存在文件時會引發IOError錯誤,也可以解理為輸出輸入錯誤
KeyError:使用了映射中不存在的關鍵字(鍵)時引發的關鍵字錯誤
IndexError:索引錯誤,使用的索引不存在,常索引超出序列範圍,什麼是索引
TypeError:類型錯誤,內建操作或是函數應於在了錯誤類型的對象時會引發類型錯誤
ZeroDivisonError:除數為0,在用除法操作時,第二個參數為0時引發了該錯誤
ValueError:值錯誤,傳給對象的參數類型不正確,像是給int()函數傳入了字符串數據類型的參數。
希望上邊的總結,對大家能夠有一些幫助,如有不到之處,也希望多多指教,相互交流進步。