Python 程式設計/錯誤
在 python 中有三種類型的錯誤;語法錯誤,邏輯錯誤 和 異常。
語法錯誤是最基本型別的錯誤。當 Python 解析器無法理解程式碼行時,就會出現語法錯誤。語法錯誤幾乎總是致命的,也就是說幾乎不可能成功執行包含語法錯誤的程式碼段。一些語法錯誤可以被捕獲和處理,比如 eval(""),但這些很少見。
在 IDLE 中,它會突出顯示語法錯誤所在的位置。大多數語法錯誤是拼寫錯誤、縮排錯誤或引數錯誤。如果您遇到此錯誤,請嘗試檢查您的程式碼中是否存在這些問題。
這些是最難找到的錯誤型別,因為它們會給出不可預測的結果,並且可能使您的程式崩潰。如果您有邏輯錯誤,可能會發生很多不同的情況。但是,這些問題很容易修復,因為您可以使用偵錯程式,它將執行程式並修復任何問題。
下面展示了一個簡單的邏輯錯誤示例,while 迴圈將編譯並執行,但是,迴圈永遠不會結束,可能會使 Python 崩潰
#Counting Sheep
#Goal: Print number of sheep up until 101.
sheep_count=1
while sheep_count<100:
print("%i Sheep"%sheep_count)
邏輯錯誤只是從程式設計目標的角度來看是錯誤的;在許多情況下,Python 按照預期的方式工作,只是沒有按照使用者的預期方式工作。上面的 while 迴圈按照 Python 的預期方式正常執行,但使用者需要的退出條件丟失了。
當 Python 解析器知道如何處理一段程式碼,但無法執行該操作時,就會出現異常。例如,嘗試使用 Python 訪問網際網路,但沒有網際網路連線;Python 直譯器知道如何處理該命令,但無法執行它。
與語法錯誤不同,異常並不總是致命的。異常可以使用try語句進行處理。
考慮以下程式碼來顯示網站 'example.com' 的 HTML。當程式執行到達 try 語句時,它將嘗試執行以下縮排的程式碼,如果由於某種原因出現錯誤(計算機未連線到網際網路或其他原因),Python 直譯器將跳到 'except:' 命令下面的縮排程式碼。
import urllib2
url = 'http://www.example.com'
try:
req = urllib2.Request(url)
response = urllib2.urlopen(req)
the_page = response.read()
print(the_page)
except:
print("We have a problem.")
另一種處理錯誤的方法是捕獲特定錯誤。
try:
age = int(raw_input("Enter your age: "))
print("You must be {0} years old.".format(age))
except ValueError:
print("Your age must be numeric.")
如果使用者輸入他的/她的年齡的數值,則輸出應如下所示
Enter your age: 5 Your age must be 5 years old.
但是,如果使用者輸入的他的/她的年齡的非數值,則在嘗試對非數值字串執行ValueError方法時會丟擲該方法,並且執行int()方法時會丟擲該方法,並且執行except子句下的程式碼。
Enter your age: five Your age must be numeric.
您也可以使用try塊,其中包含while迴圈來驗證輸入。
valid = False
while valid == False:
try:
age = int(raw_input("Enter your age: "))
valid = True # This statement will only execute if the above statement executes without error.
print("You must be {0} years old.".format(age))
except ValueError:
print("Your age must be numeric.")
該程式將提示您輸入您的年齡,直到您輸入有效的年齡。
Enter your age: five Your age must be numeric. Enter your age: abc10 Your age must be numeric. Enter your age: 15 You must be 15 years old.
在某些其他情況下,可能需要獲取有關異常的更多資訊並適當地處理它。在這種情況下,可以使用 except as 結構。
f=raw_input("enter the name of the file:")
l=raw_input("enter the name of the link:")
try:
os.symlink(f,l)
except OSError as e:
print("an error occurred linking %s to %s: %s\n error no %d"%(f,l,e.args[1],e.args[0]))
enter the name of the file:file1.txt enter the name of the link:AlreadyExists.txt an error occurred linking file1.txt to AlreadyExists.txt: File exists error no 17 enter the name of the file:file1.txt enter the name of the link:/Cant/Write/Here/file1.txt an error occurred linking file1.txt to /Cant/Write/Here/file1.txt: Permission denied error no 13