Python 新手常犯的錯誤

Python 以其簡單易懂的語法格式與其它語言造成鮮明對比,初學者遇到最多的問題就是不按照 Python 的規則來寫,即使是有編程經驗的程序員,也容易按照固有的思惟和語法格式來寫 Python 代碼,有一個外國小夥總結了一些你們常犯的錯誤,16 Common Python Runtime Errors Beginners Find,我把他翻譯過來並在原來的基礎補充了個人一些理解,但願可讓你避開這些坑。javascript

0、忘記寫冒號

在 if、elif、else、for、while、class、def 語句後面忘記添加 「:」java

if spam == 42
    print('Hello!')複製代碼

致使:SyntaxError: invalid syntaxpython

一、誤用 「=」 作等值比較

「=」 是賦值操做,而判斷兩個值是否相等是 「==」程序員

if spam = 42:
    print('Hello!')複製代碼

致使:SyntaxError: invalid syntax編程

二、使用錯誤的縮進

Python用縮進區分代碼塊,常見的錯誤用法: 函數

print('Hello!')
    print('Howdy!')複製代碼

致使:IndentationError: unexpected indent。同一個代碼塊中的每行代碼都必須保持一致的縮進量spa

if spam == 42:
    print('Hello!')
  print('Howdy!')複製代碼

致使:IndentationError: unindent does not match any outer indentation level。代碼塊結束以後縮進恢復到原來的位置.net

if spam == 42:
print('Hello!')複製代碼

致使:IndentationError: expected an indented block,「:」 後面要使用縮進翻譯

三、變量沒有定義

if spam == 42:
    print('Hello!')複製代碼

致使:NameError: name 'spam' is not definedcode

四、獲取列表元素索引位置忘記調用 len 方法

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

spam = ['cat', 'dog', 'mouse']
for i in range(spam):
    print(spam[i])複製代碼

致使:TypeError: range() integer end argument expected, got list.
正確的作法是:

spam = ['cat', 'dog', 'mouse']
for i in range(len(spam)):
    print(spam[i])複製代碼

固然,更 Pythonic 的寫法是用 enumerate

spam = ['cat', 'dog', 'mouse']
for i, item in enumerate(spam):
    print(i, item)複製代碼

五、修改字符串

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

spam = 'I have a pet cat.'
spam[13] = 'r'
print(spam)複製代碼

致使:TypeError: 'str' object does not support item assignment
正確地作法應該是:

spam = 'I have a pet cat.'
spam = spam[:13] + 'r' + spam[14:]
print(spam)複製代碼

六、字符串與非字符串鏈接

num_eggs = 12
print('I have ' + num_eggs + ' eggs.')複製代碼

致使:TypeError: cannot concatenate 'str' and 'int' objects

字符串與非字符串鏈接時,必須把非字符串對象強制轉換爲字符串類型

num_eggs = 12
print('I have ' + str(num_eggs) + ' eggs.')複製代碼

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

num_eggs = 12
print('I have %s eggs.' % (num_eggs))複製代碼

七、使用錯誤的索引位置

spam = ['cat', 'dog', 'mouse']
print(spam[3])複製代碼

致使:IndexError: list index out of range

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

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

spam = {'cat': 'Zophie', 'dog': 'Basil', 'mouse': 'Whiskers'}
print('The name of my pet zebra is ' + spam['zebra'])複製代碼

在字典對象中訪問 key 可使用 [],可是若是該 key 不存在,就會致使:KeyError: 'zebra'

正確的方式應該使用 get 方法

spam = {'cat': 'Zophie', 'dog': 'Basil', 'mouse': 'Whiskers'}
print('The name of my pet zebra is ' + spam.get('zebra'))複製代碼

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

九、用關鍵字作變量名

class = 'algebra'複製代碼

致使:SyntaxError: invalid syntax

在 Python 中不容許使用關鍵字做爲變量名。Python3 一共有33個關鍵字。

>>> 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']複製代碼

十、函數中局部變量賦值前被使用

someVar = 42

def myFunction():
    print(someVar)
    someVar = 100

myFunction()複製代碼

致使:UnboundLocalError: local variable 'someVar' referenced before assignment

當函數中有一個與全局做用域中同名的變量時,它會按照 LEGB 的順序查找該變量,若是在函數內部的局部做用域中也定義了一個同名的變量,那麼就再也不到外部做用域查找了。所以,在 myFunction 函數中 someVar 被定義了,因此 print(someVar) 就再也不外面查找了,可是 print 的時候該變量還沒賦值,因此出現了 UnboundLocalError

十一、使用自增 「++」 自減 「--」

spam = 0
spam++複製代碼

哈哈,Python 中沒有自增自減操做符,若是你是從C、Java轉過來的話,你可要注意了。你可使用 「+=」 來替代 「++」

spam = 0
spam += 1複製代碼

十二、錯誤地調用類中的方法

class Foo:
    def method1():
        print('m1')
    def method2(self):
        print("m2")

a = Foo()
a.method1()複製代碼

致使:TypeError: method1() takes 0 positional arguments but 1 was given

method1 是 Foo 類的一個成員方法,該方法不接受任何參數,調用 a.method1() 至關於調用 Foo.method1(a),但 method1 不接受任何參數,因此報錯了。正確的調用方式應該是 Foo.method1()。

須要注意的是,以上代碼都是基於 Python3 的,在 Python2 中即便是一樣的代碼出現的錯誤也不盡同樣,尤爲是最後一個例子。

博客:foofish.net
公衆號:Python之禪 (id:VTtalk),分享 Python 等技術乾貨

python之禪
相關文章
相關標籤/搜索