Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/352.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在字典中保持值的运行总数_Python_Loops_Dictionary_While Loop_Cumulative Sum - Fatal编程技术网

Python 在字典中保持值的运行总数

Python 在字典中保持值的运行总数,python,loops,dictionary,while-loop,cumulative-sum,Python,Loops,Dictionary,While Loop,Cumulative Sum,我想让用户从商店里挑选一件商品,我想使用一个循环来跟踪价格(字典中的值),在用户每次输入后进行相加并保持一个运行总数。如果用户输入的内容不在字典中,则应表示该内容不存在。 提前谢谢你的帮助 def main(): machine= {"1.shirt: $":10, "2.pants: $":15, "3.sweater: $":20,"4.socks: $":5, "5.hat: $":7} for key, value in machine.items():

我想让用户从商店里挑选一件商品,我想使用一个循环来跟踪价格(字典中的值),在用户每次输入后进行相加并保持一个运行总数。如果用户输入的内容不在字典中,则应表示该内容不存在。 提前谢谢你的帮助

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