[英]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)
try
捕获它们。 然而,由于特殊的while
循环条件,您的代码避免了迭代丢失的字典键。 这在很多层面上都是错误的。 更好地重构for i in range(len(list_goods))
循环。 否则while
在字典中的第一个键上退出循环,因此KeyError
异常不会发生。 你也冒着i
跑出边界的风险。finally
删除。 你不再需要它了。 只需在循环之外打印结果。 附注。 实际上for good in list_goods
是for good in list_goods
,如果您对 python 循环足够熟悉,请使用它,但是您需要在循环内进行更多更改。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.