有一些是語法上的錯誤,比如代碼不符合解釋器或者編譯器的語法
有一些是參數輸入錯誤,比如應該輸入整數,結果卻輸入一個字符串
有一些是邏輯上的漏洞,比如不合法的輸入或者算法上計算有些問題
有一些是程序運行錯誤,比如你要讀入文件,而傳進來的文件名不存在
訪問一個不存在的變量,比如你打印一個從來沒有定義過的變量或者你把函數名寫錯了
language='Python'
print('Welcome to study:'+Language)
>>NameError: name 'Language' is not defined
price = ruond(4.2)
print price
>>NameError: name 'ruond' is not defined
訪問一些未知的對象屬性,比如字符串裏面一些內置函數名我們拼錯了
line='Python is easy'
print line.upperr()
>>AttributeError: 'str' object has no attribute 'upperr'
比如我們訪問list的時候,索引超過了列表的最大索引
names=['XiaoMing','Lao Wang','Zhang li']
print names[3]
>>IndexError: list index out of range
有的時候寫程序寫着寫着會忘記if/elif/else/for/while/def的末尾加冒號
score=95
if score >90
print 'very good'
>>SyntaxError: invalid syntax
有時想通過索引來迭代一個list內元素,for循環中我們經常使用range()函數,但是要記得加入len()而不是直接返回這個列表
companies=['Google','Apple','Facebook']
for i in range(companies):
print i
>>TypeError: range() integer end argument expected, got list.
range()函數要用len()取列表的長度
for i in range(len(companies)):
print i
有時想把字符串和數值連接起來一起輸入,但是會有問題:
score=82
print 'Jack score is: '+str(score)
>>TypeError: cannot concatenate 'str' and 'int' objects
數字必須要轉化變成字符串才能連接:
score=82
print 'Jack score is: '+str(score)
>>Jack score is: 82
在變量使用的時候特別是在函數內部和外部用相同的變量名,經常會犯錯不信你看:
x = 10
def func():
print x
x = 1
func()
print 'Value of x is', x
>>UnboundLocalError: local variable 'x' referenced before assignment
注意在函數func()中x是局部變量,因爲在函數內部又對x進行了賦值爲1,這樣全局的x和func()中x就不是一個變量,要麼改個名字或者x=1刪掉,要麼就用加上global,表示func()中的x是用的全局的x
x = 10
def func():
global x
print x
x=1
func()
print 'Value of x is', x
>>Value of x is 1
有的時候我們會訪問一個文件,或者定義函數去傳入一個文件名,然後去讀取
很可能這個文件名根本不存在:
f=open('price.txt')
>>IOError: [Errno 2] No such file or directory: 'price.txt'
我們在運算一些數值的時候,可能會去引入除數是0的情況,
比如傳入一個列表,有可能這個列表中含有0,那麼在除的時候就會出錯
nums=[10,20,0,30]
for n in nums:
print 100/n
>>ZeroDivisionError: division by zero