date: 2020-04-01 14:25:00
updated: 2020-04-01 14:25:00
常見的Python運行時錯誤
1. SyntaxError:invalid syntax
- 忘記在 if,for,def,elif,else,class 等聲明末尾加冒號
: - 使用= 而不是 ==
= 是賦值操作符而 == 是等於比較操作
- 嘗試使用Python關鍵字作為變量名
- 不存在 ++ 或者 -- 自增自減操作符
2. IndentationError:unexpected indent 或 IndentationError:unindent does not match any outer indetation level 或 IndentationError:expected an indented block
- 錯誤的使用縮進量
記住縮進增加只用在以
:結束的語句之后,而之后必須恢復到之前的縮進格式。
3. TypeError: 'list' object cannot be interpreted as an integer
- 在 for 循環語句中忘記調用
len()通常你想要通過索引來迭代一個list或者string的元素,這需要調用 range() 函數。要記得返回len 值而不是返回這個列表。
4. TypeError: 'str' object does not support item assignment
- 嘗試修改 string 的值,而 string 是一種不可變的數據類型
錯誤:
spam = 'I have a pet cat.'
spam[13] = 'r'
print(spam)
正確:
spam = 'I have a pet cat.'
spam = spam[:13] + 'r' + spam[14:]
print(spam)
5. TypeError: Can't convert 'int' object to str implicitly
- 嘗試連接非字符串值與字符串,需通過 str(int) 來轉化
6. SyntaxError: EOL while scanning string literal
- 在字符串首尾忘記加引號
7. NameError: name 'fooba' is not defined
- 變量或者函數名拼寫錯誤
- 使用變量之前為聲明改變量
spam += 1等於spam = spam + 1,意味着 spam 需要有一個初始值
8. AttributeError: 'str' object has no attribute 'lowerr'
- 方法名拼寫錯誤
9. IndexError: list index out of range
- 引用超過list最大索引
10. KeyError:'id'
- 使用不存在的字典鍵值
在嘗試獲取字典鍵值的時候,先判斷是否存在該鍵
id = data["id"] if "id" in data.keys() else ""
11. UnboundLocalError: local variable 'foobar' referenced before assignment
- 在定義局部變量前在函數中使用局部變量(此時有與局部變量同名的全局變量存在)
12. TypeError: 'range' object does not support item assignment
- 嘗試使用 range()創建整數列表
range() 返回的是 “range object”,而不是實際的 list 值
錯誤:
spam = range(10)
spam[4] = -1
正確:
spam = list(range(10))
spam[4] = -1
13. TypeError: myMethod() takes no arguments (1 given)
- 忘記為方法的第一個參數添加self參數
class Foo():
def myMethod():
print('Hello!')
a = Foo()
a.myMethod()
