如何将字典中的值与数字相乘才能得到实数


store={'Rice':450,'Beans':200,'Egg':40,'Fish':250,'Spag':250}
bill=()
total=()
print('Welcome!!!we sell:',"n",[store])
while True:
a=input('What would you like to buy?=')
b=input('how many of each product do you want?=')
if a in store:
bill=store[a]*b
print('bill=',bill)
elif a not in store:
print('Sorry we don't have that')
else:
total=bill+total
print('Total=',total)
  • 你的if/elif/else是不可能的,因为无论a是否在dict中,你都无法进入else,所以把它放在if中。

  • 我还添加了一种方法,通过输入stop来停止循环,如果没有,您将无法停止程序并打印最终的total

  • b输入移动到if中,如果产品没有可用的,则无需询问数量

  • b上增加了int()转换

store = {'Rice': 450, 'Beans': 200, 'Egg': 40, 'Fish': 250, 'Spag': 250}
print('Welcome!!!we sell:', "n", store)
total, bill = 0, 0
while True:
a = input('What would you like to buy? ("stop" to quit): ')
print(">" + a + "<")  # For OP debug purpose only, to be removed
if a == "stop":
break
if a in store:
b = int(input('how many of each product do you want?='))
bill = store[a] * b
total += bill
print(f"Total={total} (+{bill})")
else:
print('Sorry we don't have that')
print('Total=', total)

最新更新