簡體   English   中英

如何處理 Python 中的異常處理

[英]How to handle Exception Handling in Python

如果作為字典鍵的 all_keys 變量中不存在 list_goods[i] 項目,我應該捕獲異常並將后跟值“none”的項目添加到新的字典變量中。 但是我的代碼不起作用。 感謝有人能指出我正確的方向,謝謝! Ps 我不應該在這個任務中使用 If else。

主要方法中的列表和字典

 dict_q2 = {"vinegar": [120.0, 100], "ketchup": [950, 1000],"apples": [850,1100],"oranges": [1050, 0]

}

 list_q2 = ["ketchup","oranges","pear"]

在上面的列表和字典中采用的函數

def compute_unit_prices(dict_goods, list_goods):
#dict variable with name of good as key and unit prices as values. 
return_dict = {}
all_keys = dict_goods.keys()
i =0
#Try block
try:
  while (list_goods[i] in all_keys):
   goods_name = list_goods[i]
   storage = dict_goods[goods_name]
   results = storage[0] / storage[1]
   return_dict.update({goods_name:results})
   i = i+1

except KeyError as e:
    return_dict.update({goods_name:"none"})
# If zeroDivisionError is encountered, this block of code is used
except ZeroDivisionError as e:
    results = -1
    return_dict.update({goods_name:results})
# This block of code works if errors other than the above two occurs
except:
    return_dict = {}
finally:
    print(return_dict)
  1. 您被告知要確保您的代碼拋出異常(運行時錯誤)並使用try捕獲它們。 然而,由於特殊的while循環條件,您的代碼避免了迭代丟失的字典鍵。 這在很多層面上都是錯誤的。 更好地重構for i in range(len(list_goods))循環。 否則while在字典中的第一個鍵上退出循環,因此KeyError異常不會發生。 你也冒着i跑出邊界的風險。
  2. 在循環內移動異常處理。 否則第一個異常將終止循環,並且您希望處理列表中的每個元素。
  3. finally刪除。 你不再需要它了。 只需在循環之外打印結果。

附注。 實際上for good in list_goodsfor good in list_goods ,如果您對 python 循環足夠熟悉,請使用它,但是您需要在循環內進行更多更改。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM