我有一个字典,我希望用户输入字典键和随机浮点值,然后将这两个值相乘,结果存储在变量中。循环迭代所需的次数,最后打印出最终值,该值是每个循环结果的总和。 这是我的代码:
dic = {"key1":340, "key2":110, "key3":337, "key4":319, "key5":42}
initial_val = 0
for keys in dic:
value = str(input("insert key value"))
if value == "key1":
amount = float(input("enter amount"))
product=dic.get("key1")*amount
elif value == "key2":
amount = float(input("enter amount"))
product=dic.get("key2")*amount
elif value == "key3":
amount = float(input("enter amount"))
product=dic.get("key3")*amount
elif value == "key4":
amount = float(input("enter amount"))
product=dic.get("key4")*amount
elif value == "key5":
amount = float(input("enter amount"))
product=dic.get("key5")*amount
elif value==None:
product=0
initial_val+= product
if value=="end":
break
print(initial_val)
问题是代码打印的值是期望结果+最后一次迭代的总和。我假设
print (initial_val)
需要
initial_val += product
并将其再次归结为最终结果。
问题的原因是什么?如何解决?
答案 0 :(得分:1)
你想要做的是:
dic = {"key1":340, "key2":110, "key3":337, "key4":319, "key5":42}
initial_val = 0
while True:
value = str(input("insert key value"))
if value == "end": # Break before you make the product !
break
amount = float(input("insert amount"))
product = amount * dic.get(value) # Make the product if it's not the end
initial_val += product # Make the sum
print(initial_val)
因为在您的情况下,您一直等到循环结束以测试value == "end"
。但如果value
等于"end"
,则您无需制作该产品,因为没有产品可供制作!
答案 1 :(得分:0)
elif value==None or value == "end":
product=0
答案 2 :(得分:0)
移动'如果值=="结束"'到代码的开头。以这种方式,它会在再次添加之前退出循环。