做爲Python初學者,在剛學習Python編程時,常常會看到一些報錯信息,在前面咱們沒有說起,這章節咱們會專門介紹。python
Python有兩種錯誤很容易辨認:語法錯誤和異常編程
Python 的語法錯誤或者稱之爲解析錯,是初學者常常碰到的,以下實例函數
lcassmates = ['Maichesal','asdas','Treas']
異常錯誤以下 Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'lcassmatas' is not defined
正確寫法 >>> lcassmates = ['Maichesal','asdas','Treas']; >>> lcassmates ['Maichesal', 'asdas', 'Treas']
這個例子中,函數 lcassmates 被檢查到有錯誤,是它句尾缺乏了一個結束分號(;)。學習
即使Python程序的語法是正確的,在運行它的時候,也有可能發生錯誤。運行期檢測到的錯誤被稱爲異常。spa
大多數的異常都不會被程序處理,都以錯誤信息的形式展示在這裏:操作系統
>>> 10 * (1/0) Traceback (most recent call last): File "<stdin>", line 1, in ? ZeroDivisionError: division by zero >>> 4 + spam*3 Traceback (most recent call last): File "<stdin>", line 1, in ? NameError: name 'spam' is not defined >>> '2' + 2 Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: Can't convert 'int' object to str implicitly
異常以不一樣的類型出現,這些類型都做爲信息的一部分打印出來: 例子中的類型有 ZeroDivisionError,NameError 和 TypeError。code
如下例子中,讓用戶輸入一個合法的整數,可是容許用戶中斷這個程序(使用 Control-C 或者操做系統提供的方法)。用戶中斷的信息會引起一個 KeyboardInterrupt 異常。ci
錯誤信息的前面部分顯示了異常發生的上下文,並以調用棧的形式顯示具體信息。input
>> while True: try: x = int(input("Please enter a number: ")) break except ValueError: print("Oops! That was no valid number. Try again ")
try語句按照以下方式工做;it