如何将字典中的一个值与一个数字相乘,得到一个实际值?

2024-05-29 07:11:29 发布

您现在位置:Python中文网/ 问答频道 /正文

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)

Tags: storeinyouinputeggtotalwespag
1条回答
网友
1楼 · 发布于 2024-05-29 07:11:29
  • 你的if/elif/else是不可能的,因为无论a是否在字典中,你都无法进入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)

相关问题 更多 >

    热门问题