<aside> 💡 Notion Tip: Here at Notion we use this template to help teams plan, design and develop products with the greatest chance for success. It helps teams think through their work more deeply, improves asynchronous communication with other teams, and creates space for collaboration.
</aside>
錯誤已知 (經過廣泛測試後)
scores = []
while True:
number = int(input("Enter a number: "))
if number < 0:
break
scores.append(number)
sum = 0
for score in scores:
sum += score
print("average = ", sum / len(scores))
錯誤出現如預期(稀少)
def flatten(nested):
try:
# test whether nested is a string-like object
try:
nested + ''
except TypeError: # not string-like object
pass
else: # a string-like object
raise TypeError
for sublist in nested:
for element in flatten(sublist):
yield element
except TypeError:
yield nested
使用1: 輸出 [1, 2, 3, 4, 5, 6, 7, 8]]
list(flatten([[[1], 2], 3, 4, [5, [6, 7]], 8]]))
使用2: 輸出['foo', 'bar', 'baz']
list(flatten(['foo', ['bar', ['baz']]]))
錯誤無法避免
網路連接錯誤 ⇒ 等一下課程範例會有
檔案存取錯誤
import sys
try:
f = open('myfile.txt')
s = f.readline()
i = int(s.strip())
except OSError as err:
print("OS error:", err)
except ValueError:
print("Could not convert data to an integer.")
except Exception as err:
print(f"Unexpected {err=}, {type(err)=}")
raise
my_list = [1, 2, 3, "Four", 5, 6, 7]
for element in my_list:
result = 10 + element
print(result)
這裡因為"Four"是一個字串,因此在走訪到這個元素時,會把+這個運算子當成串接字串的運算。因此Python不知道怎麼把它跟10這個整數型的常數做運算,而會拋出
TypeError的例外
for element in my_list:
try:
result = 10 + element
print(result)
except:
print("{} is not a number.".format(element))