简体   繁体   中英

keeping a running total of the values in a dictionary

I want the user to pick an item from the shop and I want to use a loop to keep track of the prices(the value in the dictionary) to add up and keep a running total after every input from user. If the user inputs something that is not in the dictionary, it should say that it does not exist. thanks in advance for help

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)

You should update the value of total every time a choice is made. See example below

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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