Python新手入門最容易犯的錯誤總結(jié)
前言
Python 以其簡單易懂的語法格式與其它語言形成鮮明對比,初學(xué)者遇到最多的問題就是不按照 Python 的規(guī)則來寫,即便是有編程經(jīng)驗的程序員,也容易按照固有的思維和語法格式來寫 Python 代碼,之前小編給大家分享過了一篇《Python新手們?nèi)菀追傅膸讉€錯誤總結(jié)》,但總結(jié)的不夠全面,最近看到有一個外國小伙總結(jié)了一些大家常犯的錯誤,16 Common Python Runtime Errors Beginners Find,索性我把他翻譯過來并在原來的基礎(chǔ)補充了我的一些理解,希望可以讓你避開這些坑。
0、忘記寫冒號
在 if、elif、else、for、while、class、def 語句后面忘記添加 “:”
if spam == 42 print('Hello!')
導(dǎo)致:SyntaxError: invalid syntax
1、誤用 “=” 做等值比較
“=” 是賦值操作,而判斷兩個值是否相等是 “==”
if spam = 42: print('Hello!')
導(dǎo)致:SyntaxError: invalid syntax
2、使用錯誤的縮進
Python用縮進區(qū)分代碼塊,常見的錯誤用法:
print('Hello!') print('Howdy!')
導(dǎo)致:IndentationError: unexpected indent
。同一個代碼塊中的每行代碼都必須保持一致的縮進量
if spam == 42: print('Hello!') print('Howdy!')
導(dǎo)致:IndentationError: unindent does not match any outer indentation level
。代碼塊結(jié)束之后縮進恢復(fù)到原來的位置
if spam == 42: print('Hello!')
導(dǎo)致:IndentationError: expected an indented block
,“:” 后面要使用縮進
3、變量沒有定義
if spam == 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'] for i in range(len(spam)): print(spam[i])
當(dāng)然,更 Pythonic 的寫法是用 enumerate
spam = ['cat', 'dog', 'mouse'] for i, item in enumerate(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 默認(rèn)返回 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 def myFunction(): print(someVar) someVar = 100 myFunction()
導(dǎo)致:UnboundLocalError: local variable 'someVar' referenced before assignment
當(dāng)函數(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() 相當(dāng)于調(diào)用 Foo.method1(a),但 method1 不接受任何參數(shù),所以報錯了。正確的調(diào)用方式應(yīng)該是 Foo.method1()。
需要注意的是:以上代碼都是基于 Python3 的,在 Python2 中即使是同樣的代碼出現(xiàn)的錯誤也不盡一樣,尤其是最后一個例子。
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者使用python能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。
相關(guān)文章
Python Django獲取URL中的數(shù)據(jù)詳解
這篇文章主要介紹了Python Django獲取URL中的數(shù)據(jù)詳解,小編覺得挺不錯的,這里分享給大家,供需要的朋友參考2021-11-11王純業(yè)的Python學(xué)習(xí)筆記 下載
這篇文章主要介紹了王純業(yè)的Python學(xué)習(xí)筆記 下載2007-02-02Python?pycryptodome庫實現(xiàn)RSA加密解密消息
本文為大家介紹了如何在?Python?中使用?RSA?公鑰加密技術(shù)來加密和解密消息,并使用?pycryptodome?庫進行實現(xiàn),有需要的朋友可以借鑒參考下,希望能夠有所幫助2024-02-02淺談keras中的目標(biāo)函數(shù)和優(yōu)化函數(shù)MSE用法
這篇文章主要介紹了淺談keras中的目標(biāo)函數(shù)和優(yōu)化函數(shù)MSE用法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06tensorflow使用神經(jīng)網(wǎng)絡(luò)實現(xiàn)mnist分類
這篇文章主要為大家詳細介紹了tensorflow使用神經(jīng)網(wǎng)絡(luò)實現(xiàn)mnist分類,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-09-09