帮助,我正在编写一个基于自动售货机的程序,并且当用户购买物品时,用户的信用将重新显示给用户,但所有价格都是十进制形式。但是当我购买商品时,它会从1减去商品价格,而不是从1.20减去商品价格。有什么想法吗?
我的代码是:
credit = raw_input("Please input your change, CAREFUL! This Machine only accepts 10p,20p,50p and £1: \n Please enter your change in Pence (Decimal form). e.g' 1.35 ")
list1= ["1", "2", "3", "4", "5"]
price1 = 0.65
price2 = 0.70
price3 = 0.50
price4 = 0.70
price5 = 0.80
while credit == 0:
credit = float(raw_input("Please input your change: ")))
products = " 1) Kinder Bueno\n 2) Doritos Chilli Heatwave\n 3) Nestle Yorkie Bar\n 4) Coca Cola(Can)\n 5) Volvic Stawberry Water"
print credit
print "The product selection is the following"
print products
selection = raw_input("Please select a product: ")
if selection == list1[0]:
new_credit = int(float(credit)) - price1
print "Your remaining credit is:",new_credit
elif selection == list1[1]:
new_credit = int(float(credit)) - price2
print "Your remaining credit is: ",new_credit
elif selection == list1[2]:
new_credit = int(float(credit)) - price3
print "Your remaining credit is: ",new_credit
elif selection == list1[3]:
new_credit = int(float(credit)) - price4
print "Your remaining credit is: ",new_credit
elif selection == list1[0]:
new_credit = int(float(credit)) - price5
print "Your remaining credit is: ",new_credit
它仍会截断并返回以下内容:
Please input your change, CAREFUL! This Machine only accepts 10p,20p,50p and £1:
Please enter your change in Pence (Decimal form). e.g' 1.35 1.35
1.35
The product selection is the following
1) Kinder Bueno
2) Doritos Chilli Heatwave
3) Nestle Yorkie Bar
4) Coca Cola(Can)
5) Volvic Stawberry Water
Please select a product: 1
Your remaining credit is: 0.35
答案 0 :(得分:0)
所以你的代码给了我很多麻烦。我做了一些改变,使事情变得更加诡异......
例如,有很多事情要做,在无效输入上捕获错误,在扣除价格之前检查可用信用等等......
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
使用元组列表,您可以轻松获得最低价格,以确保用户有足够的实际购买价格:
min_price = min(products, key=lambda x:x[1])[1]
获得价格最低的元组,只存储min_price