[Solved] Decimal Subtraction [closed]


So your code bugged me alot. I made some changes to make things more pythonic…

  1. Instead of separate lists for your menu, I made it a list of tuples containing the product and it’s price
  2. I fixed your float casts

There’s alot to be done for example, catching errors on invalid inputs, checking for available credit before subtracting price, etc…

products = [
    ("Kinder Bueno", 0.65),
    ("Doritos Chilli Heatwave", 0.70),
    ("Nestle Yorkie Bar", 0.50),
    ("Coca Cola(Can)", 0.70),
    ("Volvic Stawberry Water", 0.80)
]  
min_price = min(products, key=lambda x:x[1])[1]
credit = float(raw_input("Please input your change, CAREFUL! This Machine only accepts 10p,20p,50p and £1: \n Please enter your change in Pence, at least {0} (Decimal form). e.g' 1.35  ".format(min_price)))

while credit < min_price:
    credit += float(raw_input("Please input more change, you have {0} available, please input at least {1} more: ".format(credit, min_price - credit)))

print "You have {0} credit available.".format(credit)
print "The product selection is the following:"
for i, (product, price) in enumerate(products):
    print "  {0}) {1} {2}".format(i, product, price)

selection = int(raw_input("Please select a product: "))

if 0 >= selection < len(products):
    product, price = products[selection]
    print "You bought {0} for {1}".format(product, price)
    new_credit = credit - price
    print "Your remaining credit is: ", new_credit

With the list of tuples, you can easily get a minimum price to ensure the user has enough to actually buy something:

min_price = min(products, key=lambda x:x[1])[1]

which gets the tuple with the lowest price and stores just the price in min_price

5

solved Decimal Subtraction [closed]