Jan-15-2020, 01:17 PM
price_mapping = { "onion": 50, "carrot": 20, "tomato": 10 } # I changed the mapping. The values are now integers. # Are the prices in the smallest currency unit? # If you calculate with prices, you should use integer or decimal # Otherwise you get some inaccuracy # A float can not represent all decimal values. This is impossible. # summing up many floats will produce a growing inaccuracy. # summing up many integers has no error # Print the price list print("These are the prices of vegetables") for name, price in price_mapping.items(): print(name, price) # formatting is your task # and you should look what dicts are. # they have methods like keys(), values(), items() vegetables = [] while True: vegetable = input("Enter the name of vegetable (empty to sum up): ").strip().lower() # the strip() method removes white space # the lower() method convert everything into lower case # this is less error prune, if the user for example use upper case letters # or whitespaces before or after the word. if not vegetable: # this is the break condition # if the string vegetable is empty # the loop stops and the code after the # loop is executed break if vegetable not in price_mapping: print('is not in price list') continue # ask again the question # this line is reached, if vegetable is not an empty string and # if vegetable is in price list vegetables.append(price_mapping[vegetable]) # look what lists are. append puts the items to the end of a list # now you can just sum the floats result = sum(vegetables) # the function sum takes any iterables and applies + for all elements. print('You have to pay', result, 'bananas') # Or you could use string formatting # print(f'You have to pay {result} bananas')
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
All humans together. We don't need politicians!