Python運(yùn)行的17個(gè)時(shí)新手常見錯(cuò)誤小結(jié)
更新時(shí)間:2012年08月07日 23:48:01 作者:
當(dāng)初學(xué) Python 時(shí),想要弄懂 Python 的錯(cuò)誤信息的含義可能有點(diǎn)復(fù)雜。這里列出了常見的的一些讓你程序 crash 的運(yùn)行時(shí)錯(cuò)誤
1)忘記在 if , elif , else , for , while , class ,def 聲明末尾添加 :(導(dǎo)致 “SyntaxError :invalid syntax”)
該錯(cuò)誤將發(fā)生在類似如下代碼中:
if spam == 42
print('Hello!')
2)使用 = 而不是 ==(導(dǎo)致“SyntaxError: invalid syntax”)
= 是賦值操作符而 == 是等于比較操作。該錯(cuò)誤發(fā)生在如下代碼中:
if spam = 42:
print('Hello!')
3)錯(cuò)誤的使用縮進(jìn)量。(導(dǎo)致“IndentationError:unexpected indent”、“IndentationError:unindent does not match any outer indetation level”以及“IndentationError:expected an indented block”)
記住縮進(jìn)增加只用在以:結(jié)束的語句之后,而之后必須恢復(fù)到之前的縮進(jìn)格式。該錯(cuò)誤發(fā)生在如下代碼中:
print('Hello!')
print('Howdy!')
或者:
if spam == 42:
print('Hello!')
print('Howdy!')
或者:
if spam == 42:
print('Hello!')
4)在 for 循環(huán)語句中忘記調(diào)用 len() (導(dǎo)致“TypeError: 'list' object cannot be interpreted as an integer”)
通常你想要通過索引來迭代一個(gè)list或者string的元素,這需要調(diào)用 range() 函數(shù)。要記得返回len 值而不是返回這個(gè)列表。
該錯(cuò)誤發(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ù)類型,該錯(cuò)誤發(fā)生在如下代碼中:
spam = 'I have a pet cat.'
spam[13] = 'r'
print(spam)
而你實(shí)際想要這樣做:
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”)
該錯(cuò)誤發(fā)生在如下代碼中:
numEggs = 12
print('I have ' + numEggs + ' eggs.')
而你實(shí)際想要這樣做:
numEggs = 12
print('I have ' + str(numEggs) + ' eggs.')
或者:
numEggs = 12
print('I have %s eggs.' % (numEggs))
7)在字符串首尾忘記加引號(hào)(導(dǎo)致“SyntaxError: EOL while scanning string literal”)
該錯(cuò)誤發(fā)生在如下代碼中:
print(Hello!')
或者:
print('Hello!)
或者:
myName = 'Al'
print('My name is ' + myName + . How are you?')
8)變量或者函數(shù)名拼寫錯(cuò)誤(導(dǎo)致“NameError: name 'fooba' is not defined”)
該錯(cuò)誤發(fā)生在如下代碼中:
foobar = 'Al'
print('My name is ' + fooba)
或者:
spam = ruond(4.2)
或者:
spam = Round(4.2)
9)方法名拼寫錯(cuò)誤(導(dǎo)致 “AttributeError: 'str' object has no attribute 'lowerr'”)
該錯(cuò)誤發(fā)生在如下代碼中:
spam = 'THIS IS IN LOWERCASE.'
spam = spam.lowerr()
10)引用超過list最大索引(導(dǎo)致“IndexError: list index out of range”)
該錯(cuò)誤發(fā)生在如下代碼中:
spam = ['cat', 'dog', 'mouse']
print(spam[6])
11)使用不存在的字典鍵值(導(dǎo)致“KeyError:‘spam'”)
該錯(cuò)誤發(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)鍵不能用作變量名,該錯(cuò)誤發(fā)生在如下代碼中:
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)在一個(gè)定義新變量中使用增值操作符(導(dǎo)致“NameError: name 'foobar' is not defined”)
不要在聲明變量時(shí)使用0或者空字符串作為初始值,這樣使用自增操作符的一句spam += 1等于spam = spam + 1,這意味著spam需要指定一個(gè)有效的初始值。
該錯(cuò)誤發(fā)生在如下代碼中:
spam = 0
spam += 42
eggs += 42
14)在定義局部變量前在函數(shù)中使用局部變量(此時(shí)有與局部變量同名的全局變量存在)(導(dǎo)致“UnboundLocalError: local variable 'foobar' referenced before assignment”)
在函數(shù)中使用局部變來那個(gè)而同時(shí)又存在同名全局變量時(shí)是很復(fù)雜的,使用規(guī)則是:如果在函數(shù)中定義了任何東西,如果它只是在函數(shù)中使用那它就是局部的,反之就是全局變量。
這意味著你不能在定義它之前把它當(dāng)全局變量在函數(shù)中使用。
該錯(cuò)誤發(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í)你想要得到一個(gè)有序的整數(shù)列表,所以 range() 看上去是生成此列表的不錯(cuò)方式。然而,你需要記住 range() 返回的是 “range object”,而不是實(shí)際的 list 值。
該錯(cuò)誤發(fā)生在如下代碼中:
spam = range(10)
spam[4] = -1
也許這才是你想做:
spam = list(range(10))
spam[4] = -1
(注意:在 Python 2 中 spam = range(10) 是能行的,因?yàn)樵?Python 2 中 range() 返回的是list值,但是在 Python 3 中就會(huì)產(chǎn)生以上錯(cuò)誤)
16)不錯(cuò)在 ++ 或者 -- 自增自減操作符。(導(dǎo)致“SyntaxError: invalid syntax”)
如果你習(xí)慣于例如 C++ , Java , PHP 等其他的語言,也許你會(huì)想要嘗試使用 ++ 或者 -- 自增自減一個(gè)變量。在Python中是沒有這樣的操作符的。
該錯(cuò)誤發(fā)生在如下代碼中:
spam = 1
spam++
也許這才是你想做的:
17)忘記為方法的第一個(gè)參數(shù)添加self參數(shù)(導(dǎo)致“TypeError: myMethod() takes no arguments (1 given)”)
該錯(cuò)誤發(fā)生在如下代碼中:
class Foo():
def myMethod():
print('Hello!')
a = Foo()
a.myMethod()
該錯(cuò)誤將發(fā)生在類似如下代碼中:
復(fù)制代碼 代碼如下:
if spam == 42
print('Hello!')
2)使用 = 而不是 ==(導(dǎo)致“SyntaxError: invalid syntax”)
= 是賦值操作符而 == 是等于比較操作。該錯(cuò)誤發(fā)生在如下代碼中:
復(fù)制代碼 代碼如下:
if spam = 42:
print('Hello!')
3)錯(cuò)誤的使用縮進(jìn)量。(導(dǎo)致“IndentationError:unexpected indent”、“IndentationError:unindent does not match any outer indetation level”以及“IndentationError:expected an indented block”)
記住縮進(jìn)增加只用在以:結(jié)束的語句之后,而之后必須恢復(fù)到之前的縮進(jìn)格式。該錯(cuò)誤發(fā)生在如下代碼中:
復(fù)制代碼 代碼如下:
print('Hello!')
print('Howdy!')
或者:
if spam == 42:
print('Hello!')
print('Howdy!')
或者:
if spam == 42:
print('Hello!')
4)在 for 循環(huán)語句中忘記調(diào)用 len() (導(dǎo)致“TypeError: 'list' object cannot be interpreted as an integer”)
通常你想要通過索引來迭代一個(gè)list或者string的元素,這需要調(diào)用 range() 函數(shù)。要記得返回len 值而不是返回這個(gè)列表。
該錯(cuò)誤發(fā)生在如下代碼中:
復(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ù)類型,該錯(cuò)誤發(fā)生在如下代碼中:
復(fù)制代碼 代碼如下:
spam = 'I have a pet cat.'
spam[13] = 'r'
print(spam)
而你實(shí)際想要這樣做:
復(fù)制代碼 代碼如下:
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”)
該錯(cuò)誤發(fā)生在如下代碼中:
復(fù)制代碼 代碼如下:
numEggs = 12
print('I have ' + numEggs + ' eggs.')
而你實(shí)際想要這樣做:
復(fù)制代碼 代碼如下:
numEggs = 12
print('I have ' + str(numEggs) + ' eggs.')
或者:
numEggs = 12
print('I have %s eggs.' % (numEggs))
7)在字符串首尾忘記加引號(hào)(導(dǎo)致“SyntaxError: EOL while scanning string literal”)
該錯(cuò)誤發(fā)生在如下代碼中:
復(fù)制代碼 代碼如下:
print(Hello!')
或者:
print('Hello!)
或者:
myName = 'Al'
print('My name is ' + myName + . How are you?')
8)變量或者函數(shù)名拼寫錯(cuò)誤(導(dǎo)致“NameError: name 'fooba' is not defined”)
該錯(cuò)誤發(fā)生在如下代碼中:
復(fù)制代碼 代碼如下:
foobar = 'Al'
print('My name is ' + fooba)
或者:
spam = ruond(4.2)
或者:
spam = Round(4.2)
9)方法名拼寫錯(cuò)誤(導(dǎo)致 “AttributeError: 'str' object has no attribute 'lowerr'”)
該錯(cuò)誤發(fā)生在如下代碼中:
復(fù)制代碼 代碼如下:
spam = 'THIS IS IN LOWERCASE.'
spam = spam.lowerr()
10)引用超過list最大索引(導(dǎo)致“IndexError: list index out of range”)
該錯(cuò)誤發(fā)生在如下代碼中:
復(fù)制代碼 代碼如下:
spam = ['cat', 'dog', 'mouse']
print(spam[6])
11)使用不存在的字典鍵值(導(dǎo)致“KeyError:‘spam'”)
該錯(cuò)誤發(fā)生在如下代碼中:
復(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)鍵不能用作變量名,該錯(cuò)誤發(fā)生在如下代碼中:
復(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)在一個(gè)定義新變量中使用增值操作符(導(dǎo)致“NameError: name 'foobar' is not defined”)
不要在聲明變量時(shí)使用0或者空字符串作為初始值,這樣使用自增操作符的一句spam += 1等于spam = spam + 1,這意味著spam需要指定一個(gè)有效的初始值。
該錯(cuò)誤發(fā)生在如下代碼中:
復(fù)制代碼 代碼如下:
spam = 0
spam += 42
eggs += 42
14)在定義局部變量前在函數(shù)中使用局部變量(此時(shí)有與局部變量同名的全局變量存在)(導(dǎo)致“UnboundLocalError: local variable 'foobar' referenced before assignment”)
在函數(shù)中使用局部變來那個(gè)而同時(shí)又存在同名全局變量時(shí)是很復(fù)雜的,使用規(guī)則是:如果在函數(shù)中定義了任何東西,如果它只是在函數(shù)中使用那它就是局部的,反之就是全局變量。
這意味著你不能在定義它之前把它當(dāng)全局變量在函數(shù)中使用。
該錯(cuò)誤發(fā)生在如下代碼中:
復(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í)你想要得到一個(gè)有序的整數(shù)列表,所以 range() 看上去是生成此列表的不錯(cuò)方式。然而,你需要記住 range() 返回的是 “range object”,而不是實(shí)際的 list 值。
該錯(cuò)誤發(fā)生在如下代碼中:
復(fù)制代碼 代碼如下:
spam = range(10)
spam[4] = -1
也許這才是你想做:
復(fù)制代碼 代碼如下:
spam = list(range(10))
spam[4] = -1
(注意:在 Python 2 中 spam = range(10) 是能行的,因?yàn)樵?Python 2 中 range() 返回的是list值,但是在 Python 3 中就會(huì)產(chǎn)生以上錯(cuò)誤)
16)不錯(cuò)在 ++ 或者 -- 自增自減操作符。(導(dǎo)致“SyntaxError: invalid syntax”)
如果你習(xí)慣于例如 C++ , Java , PHP 等其他的語言,也許你會(huì)想要嘗試使用 ++ 或者 -- 自增自減一個(gè)變量。在Python中是沒有這樣的操作符的。
該錯(cuò)誤發(fā)生在如下代碼中:
復(fù)制代碼 代碼如下:
spam = 1
spam++
也許這才是你想做的:
復(fù)制代碼 代碼如下:
spam = 1
spam += 1
spam += 1
17)忘記為方法的第一個(gè)參數(shù)添加self參數(shù)(導(dǎo)致“TypeError: myMethod() takes no arguments (1 given)”)
該錯(cuò)誤發(fā)生在如下代碼中:
復(fù)制代碼 代碼如下:
class Foo():
def myMethod():
print('Hello!')
a = Foo()
a.myMethod()
相關(guān)文章
PyTorch中Tensor的維度變換實(shí)現(xiàn)
這篇文章主要介紹了PyTorch中Tensor的維度變換實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-08-08
Python中xlsx文件轉(zhuǎn)置操作詳解(行轉(zhuǎn)列和列轉(zhuǎn)行)
很多時(shí)候我們處理的Excel表格并不是我們想要的樣子,需要將表格的形式進(jìn)行相應(yīng)轉(zhuǎn)換后進(jìn)行數(shù)據(jù)分析操作,下面這篇文章主要給大家介紹了關(guān)于Python中xlsx文件轉(zhuǎn)置操作(行轉(zhuǎn)列和列轉(zhuǎn)行)的相關(guān)資料,需要的朋友可以參考下2022-07-07
深入探究python中Pandas庫處理缺失數(shù)據(jù)和數(shù)據(jù)聚合
在本篇文章中,我們將深入探討Pandas庫中兩個(gè)重要的數(shù)據(jù)處理功能:處理缺失數(shù)據(jù)和數(shù)據(jù)聚合,文中有詳細(xì)的代碼示例,對我們的學(xué)習(xí)或工作有一定的幫助,需要的朋友可以參考下2023-07-07
Python中獲取網(wǎng)頁狀態(tài)碼的兩個(gè)方法
這篇文章主要介紹了Python中獲取網(wǎng)頁狀態(tài)碼的兩個(gè)方法,分別使用urllib模塊和requests模塊實(shí)現(xiàn),需要的朋友可以參考下2014-11-11
tensorflow基于CNN實(shí)戰(zhàn)mnist手寫識(shí)別(小白必看)
這篇文章主要介紹了tensorflow基于CNN實(shí)戰(zhàn)mnist手寫識(shí)別(小白必看),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-07-07
Python實(shí)戰(zhàn)基礎(chǔ)之繪制餅狀圖分析商品庫存
餅狀圖(pie chart)一般用于描述分類型數(shù)據(jù)的相對頻數(shù)或百分?jǐn)?shù)頻數(shù)分布,呈現(xiàn)部分與總體的關(guān)系,下面這篇文章主要給大家介紹了關(guān)于Python實(shí)戰(zhàn)基礎(chǔ)之繪制餅狀圖分析商品庫存的相關(guān)資料,需要的朋友可以參考下2022-07-07
Pytorch實(shí)現(xiàn)Fashion-mnist分類任務(wù)全過程
這篇文章主要介紹了Pytorch實(shí)現(xiàn)Fashion-mnist分類任務(wù)全過程,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-12-12
Python使用logging模塊實(shí)現(xiàn)打印log到指定文件的方法
這篇文章主要介紹了Python使用logging模塊實(shí)現(xiàn)打印log到指定文件的方法,結(jié)合實(shí)例形式分析了Python logging模塊的原理及相關(guān)日志輸出操作技巧,需要的朋友可以參考下2018-09-09

