跳轉到內容

Python 3 非程式設計師教程/處理不完美

來自華夏公益教科書,開放的書籍,開放的世界

...或如何處理錯誤

[編輯 | 編輯原始碼]

使用 with 關閉檔案

[編輯 | 編輯原始碼]

我們使用 "with" 語句來開啟和關閉檔案。[1][2]

with open("in_test.txt", "rt") as in_file:
    with open("out_test.txt", "wt") as out_file:
        text = in_file.read()
        data = parse(text)
        results = encode(data)
        out_file.write(results)
    print( "All done." )

如果這段程式碼中的任何地方出現錯誤(其中一個檔案不可訪問,parse() 函式因損壞資料而崩潰等),"with" 語句保證所有檔案最終都能正常關閉。關閉檔案只是意味著檔案被我們的程式“清理”和“釋放”,以便在另一個程式中使用。


Clipboard

待辦事項
"使用 with 關閉檔案" 部分對於非程式設計師教程來說是否過於詳細?如果是,將其移動到其他 Python 華夏公益教科書 (主題:Python 程式語言)


使用 try 捕獲錯誤

[編輯 | 編輯原始碼]

所以你現在擁有了一個完美的程式,它執行得非常完美,只有一個細節,它會在無效的使用者輸入時崩潰。不要害怕,因為 Python 為你準備了一個特殊的控制結構。它被稱為 `try`,它試圖做一些事情。以下是一個有問題的程式示例

print("Type Control C or -1 to exit")
number = 1
while number != -1:
   number = int(input("Enter a number: "))
   print("You entered:", number)

注意,當你輸入 `@#&` 時,它會輸出類似於以下內容:

Traceback (most recent call last):
 File "try_less.py", line 4, in <module>
   number = int(input("Enter a number: "))
ValueError: invalid literal for int() with base 10: '\\@#&'

正如你所看到的,`int()` 函式對數字 `@#&` 很不滿意(它應該如此)。最後一行顯示了問題所在;Python 發現了一個 `ValueError`。我們的程式如何處理這種情況?我們首先要做的就是:將可能出現錯誤的地方放在 `try` 塊中,其次是:告訴 Python 我們希望如何處理 `ValueError`。以下程式就是這樣做的

print("Type Control C or -1 to exit")
number = 1
while number != -1:
    try:
        number = int(input("Enter a number: "))
        print("You entered:", number)
    except ValueError:
        print("That was not a number.")

現在,當我們執行新程式並輸入 `@#&` 時,它會告訴我們“這不是數字”。並繼續它之前的操作。

當你的程式一直遇到你知道如何處理的錯誤時,將程式碼放在 `try` 塊中,並將處理錯誤的方式放在 `except` 塊中。

至少更新電話號碼程式(在 字典 部分),以便它在使用者在選單中沒有輸入任何資料時不會崩潰。

解決方案
def print_menu():
	print('1. Print Phone Numbers')
	print('2. Add a Phone Number')
	print('3. Remove a Phone Number')
	print('4. Lookup a Phone Number')
	print('5. Quit')
	print()

numbers = {}
menu_choice = 0
print_menu()
while menu_choice != 5:
	try:
		menu_choice = int(input("Type in a number (1-5): "))
		if menu_choice == 1:
			print("Telephone Numbers:")
			for x in numbers.keys():
				print("Name: ", x, "\tNumber:", numbers[x])
			print()
		elif menu_choice == 2:
			print("Add Name and Number")
			name = input("Name: ")
			phone = input("Number: ")
			numbers[name] = phone
		elif menu_choice == 3:
			print("Remove Name and Number")
			name = input("Name: ")
			if name in numbers:
				del numbers[name]
			else:
				print(name, "was not found")
		elif menu_choice == 4:
			print("Lookup Number")
			name = input("Name: ")
			if name in numbers:
				print("The number is", numbers[name])
			else:
				print(name, "was not found")
		elif menu_choice != 5:
			print_menu()
	except ValueError:
		print("That was not a number.")
Python 3 非程式設計師教程
 ← 檔案 I/O 處理不完美 遞迴 → 
  1. "'with' 語句"
  2. 'Python "with" 語句示例'
華夏公益教科書