Python入門最容易犯的錯誤

Python 以其簡單易懂的語法格式與其它語言形成鮮明對比,初學(xué)者遇到最多的問題就是不按照 Python 的規(guī)則來寫,即便是有編程經(jīng)驗的程序員,也容易按照固有的思維和語法格式來寫 Python 代碼,有一個外國小伙總結(jié)了一些大家常犯的錯誤,16 Common Python Runtime Errors Beginners Find,我把他翻譯過來并在原來的基礎(chǔ)補充了我的一些理解,希望可以讓你避開這些坑。

0、忘記寫冒號

在 if、elif、else、for、while、class、def 語句后面忘記添加 “:”

ifspam ==42

print('Hello!')

導(dǎo)致:SyntaxError: invalid syntax

1、誤用 “=” 做等值比較

“=” 是賦值操作,而判斷兩個值是否相等是 “==”

ifspam =42:

print('Hello!')

導(dǎo)致:SyntaxError: invalid syntax

2、使用錯誤的縮進

Python用縮進區(qū)分代碼塊,常見的錯誤用法:

print('Hello!')

print('Howdy!')

導(dǎo)致:IndentationError: unexpected indent。同一個代碼塊中的每行代碼都必須保持一致的縮進量

ifspam ==42:

print('Hello!')

print('Howdy!')

導(dǎo)致:IndentationError: unindent does not match any outer indentation level。代碼塊結(jié)束之后縮進恢復(fù)到原來的位置

ifspam ==42:

print('Hello!')

導(dǎo)致:IndentationError: expected an indented block,“:” 后面要使用縮進

3、變量沒有定義

ifspam ==42:

print('Hello!')

導(dǎo)致:NameError: name ‘spam’ is not defined

4、獲取列表元素索引位置忘記調(diào)用 len 方法

通過索引位置獲取元素的時候,忘記使用 len 函數(shù)獲取列表的長度。

spam = ['cat', 'dog', 'mouse']

for i in range(spam):

? ?print(spam[i])

導(dǎo)致:TypeError: range() integer end argument expected, got list.

正確的做法是:

spam = ['cat','dog','mouse']

foriinrange(len(spam)):

print(spam[i])

當然,更 Pythonic 的寫法是用 enumerate

spam = ['cat','dog','mouse']

fori, iteminenumerate(spam):

print(i, item)

5、修改字符串

字符串一個序列對象,支持用索引獲取元素,但它和列表對象不同,字符串是不可變對象,不支持修改。

spam ='I have a pet cat.'

spam[13] ='r'

print(spam)

導(dǎo)致:TypeError: ‘str’ object does not support item assignment

正確地做法應(yīng)該是:

spam ='I have a pet cat.'

spam = spam[:13] +'r'+ spam[14:]

print(spam)

6、字符串與非字符串連接

num_eggs = 12

print('I have ' + num_eggs + ' eggs.')

導(dǎo)致:TypeError: cannot concatenate ‘str’ and ‘int’ objects

字符串與非字符串連接時,必須把非字符串對象強制轉(zhuǎn)換為字符串類型

num_eggs =12

print('I have '+ str(num_eggs) +' eggs.')

或者使用字符串的格式化形式

num_eggs =12

print('I have %s eggs.'% (num_eggs))

7、使用錯誤的索引位置

spam = ['cat','dog','mouse']

print(spam[3])

導(dǎo)致:IndexError: list index out of range

列表對象的索引是從0開始的,第3個元素應(yīng)該是使用 spam[2] 訪問

8、字典中使用不存在的鍵

spam = {'cat':'Zophie','dog':'Basil','mouse':'Whiskers'}

print('The name of my pet zebra is '+ spam['zebra'])

在字典對象中訪問 key 可以使用[],但是如果該 key 不存在,就會導(dǎo)致:KeyError: ‘zebra’

正確的方式應(yīng)該使用 get 方法

spam = {'cat':'Zophie','dog':'Basil','mouse':'Whiskers'}

print('The name of my pet zebra is '+ spam.get('zebra'))

key 不存在時,get 默認返回 None

9、用關(guān)鍵字做變量名

class = 'algebra'

導(dǎo)致:SyntaxError: invalid syntax

在 Python 中不允許使用關(guān)鍵字作為變量名。Python3 一共有33個關(guān)鍵字。

>>> import keyword

>>> print(keyword.kwlist)

['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

10、函數(shù)中局部變量賦值前被使用

someVar =42

defmyFunction():

print(someVar)

someVar =100

myFunction()

導(dǎo)致:UnboundLocalError: local variable ‘someVar’ referenced before assignment

當函數(shù)中有一個與全局作用域中同名的變量時,它會按照 LEGB 的順序查找該變量,如果在函數(shù)內(nèi)部的局部作用域中也定義了一個同名的變量,那么就不再到外部作用域查找了。因此,在 myFunction 函數(shù)中 someVar 被定義了,所以 print(someVar) 就不再外面查找了,但是 print 的時候該變量還沒賦值,所以出現(xiàn)了 UnboundLocalError

11、使用自增 “++” 自減 “—”

spam =0

spam++

哈哈,Python 中沒有自增自減操作符,如果你是從C、Java轉(zhuǎn)過來的話,你可要注意了。你可以使用 “+=” 來替代 “++”

spam =0

spam +=1

12、錯誤地調(diào)用類中的方法

class Foo:

? ?def method1():

? ? ? ?print('m1')

? ?def method2(self):

? ? ? ?print("m2")

a = Foo()

a.method1()

導(dǎo)致:TypeError: method1() takes 0 positional arguments but 1 was given

method1 是 Foo 類的一個成員方法,該方法不接受任何參數(shù),調(diào)用 a.method1() 相當于調(diào)用 Foo.method1(a),但 method1 不接受任何參數(shù),所以報錯了。正確的調(diào)用方式應(yīng)該是 Foo.method1()。

需要注意的是,以上代碼都是基于 Python3 的,在 Python2 中即使是同樣的代碼出現(xiàn)的錯誤也不盡一樣,尤其是最后一個例子。

在學(xué)習(xí)python中有任何困難不懂的可以加入我的python交流學(xué)習(xí)QQ群:932749660,多多交流問題,互幫互助,群里有不錯的學(xué)習(xí)教程和開發(fā)工具。分享學(xué)習(xí)

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容