繁体   English   中英

保持字典中值的运行总和

[英]keeping a running total of the values in a dictionary

我希望用户从商店中挑选一件商品,并且我希望使用一个循环来跟踪价格(字典中的值)以在用户每次输入后进行累加并保持运行总计。 如果用户输入了字典中没有的东西,它应该说它不存在。 提前感谢您的帮助

def main():
    machine= {"1.shirt: $":10, "2.pants: $":15, "3.sweater: $":20,"4.socks: $":5, "5.hat: $":7}


    for key, value in machine.items():
       print(key,value)
       print("------------------------------")
       selection = input("Please choose the number of the item you would like to purchase: ")

    total=0
    for i in machine:
       if selection=="1":
           print("You chose shirt and your total is: $", machine["1.shirt: $"])
       elif selection=="2":
           print("You chose shirt and your total is: $", machine["2.pants: $"])
       elif selection=="3":
           print("You chose shirt and your total is: $", machine["3.sweater: $"])
       elif selection=="4":
           print("You chose shirt and your total is: $", machine["4.socks: $"])
       elif selection=="5":
           print("You chose shirt and your total is: $", machine["5.hat: $"])
      else:
           print("Your option does not exist. Your total is: ",total)

每次做出选择时,您都应该更新 total 的值。 请参阅下面的示例

def main():
    machine= {"1.shirt: $":10, "2.pants: $":15, "3.sweater: $":20,"4.socks: $":5, "5.hat: $":7}
    total=0
    for key, value in machine.items():
       print(key,value)
       print("------------------------------")
    while True: # Keep Looping
       selection = input("Please choose the number of the item you would like to purchase: ")

       if selection=="1":
           total += machine["1.shirt: $"];
           print("You chose shirt and your total is: $", total)
       elif selection=="2":
           total += machine["2.pants: $"];
           print("You chose shirt and your total is: $", total)
       else:
           print("Your option does not exist. Your total is: ",total)
           break

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM