如何在Python中处理异常处理
如果列表商品[i]项不存在于作为字典关键字的所有关键字变量中,我应该捕获一个异常,并将该项后跟一个值“none”添加到新的字典变量中。但是,我的代码不起作用。如果有人能给我指出正确的方向,我将不胜感激,谢谢!注意:如果本作业中有其他内容,我不应该使用 主方法中的列表和字典如何在Python中处理异常处理,python,Python,如果列表商品[i]项不存在于作为字典关键字的所有关键字变量中,我应该捕获一个异常,并将该项后跟一个值“none”添加到新的字典变量中。但是,我的代码不起作用。如果有人能给我指出正确的方向,我将不胜感激,谢谢!注意:如果本作业中有其他内容,我不应该使用 主方法中的列表和字典 dict_q2 = {"vinegar": [120.0, 100], "ketchup": [950, 1000],"apples": [850,1100],&q
dict_q2 = {"vinegar": [120.0, 100], "ketchup": [950, 1000],"apples": [850,1100],"oranges": [1050, 0]
}
函数接受上述列表并记录
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
循环条件,您的代码避免了迭代丢失的字典键。这在很多层面上都是错误的。更好地重构到范围内的i(len(list_货物))
循环。否则,while
将在字典的第一个键上退出循环,因此KeyError
异常不会发生。此外,您还可能面临i
超出边界的风险
。你不再需要它了。只需在循环外部打印结果实际上,
for good in list\u goods
更像python,如果你对python循环感到满意,就使用它,但是你需要在循环内部做更多的更改。为什么你“应该抛出一个异常”?如果列出商品[i]
不在所有关键字中,为什么你不能简单地采取补救措施呢?这里有很多问题。首先,如果在此处引发异常,goods\u name
变量可能未定义:while(在所有关键字中列出商品[i])
。此外,如果抛出异常,您不会更改i
的值,因此您会不断重复使用相同的值。最后,除了KeyError as e
——这里变量e
不用于任何东西,为什么要用它呢?顺便说一句,如果你知道问题出在哪里,它可能会有所帮助。令人惊讶的是,您的代码即使在我的电脑上运行时不正确。{'ketchup':0.95,'oranges':-1}
面临的问题是,您获得的输出是答案的一部分。然而,我应该有一个额外的“梨”:没有。因此,对于不在dict_q2中的pear,其值将自动设置为none。我尝试过使用key error exception,但没有用,因为我不应该使用If-else语句。我明白了。检查我的答案。为什么不最后使用
Else
仅在try
块成功时执行,但在任何情况下都希望打印生成的词典,因此finally
是合适的。
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)