【发布时间】:2015-10-03 04:52:01
【问题描述】:
我需要为一台只接受某些硬币的自动售货机编码
“它将允许您输入 1p、2p、5p、10p、20p、50p 和 1.00 英镑,但它会拒绝 2.00 英镑的硬币”
我有一个列表,里面有浮点值:
coins = ["0.01","0.02","0.05","0.10","0.20","0.50","1"]
这些是硬币,我希望用户输入
coin = float(input())
在这之后我有
def balance():
coin = float(input("Please enter your coins."))
if coin not in coins:
print("Incorrect coin amount! Please remember we don't accept 2 pound coins!")
else:
print("Correct coin amount. The coins have been added to your balance")
fb = fb + coin
我无法让它工作,因为它只会打印“硬币数量不正确!请记住我们不接受 2 磅硬币!”。 在此之后,我已经在这里尝试了这个解决方案:Python Coding - Vending machine - How to get the user to only enter certain coins? 我认为这意味着我需要更改我的 float(input()) 并且所有内容都浮动为 int,因此将 0.01 (1p) 更改为 1。但是,当我这样做时,我仍然得到了
'int' object has no attribute 'split'
在这段代码中使用时
dict = {"KitKat":"80p", "Coca-Cola":"85p", "DairyMilk":"80p","Walkers Crisps":"90p"}
coins = ["1","2","5","10","20","50","100"]
def balance():
inp = int(input("Please enter your coins. Please enter in pence, for example 1 pound = 100"))
if any(int(coin) not in value for coin in inp.split()):
print("Machine doesn't accept these coins")
else:
print("Correct coin amount. The coins have been added to your balance")
fb = fb + coin
def items():
print (" 1. KitKat:" , dict['KitKat'])
print (" 2. Coca-Cola:", dict['Coca-Cola'])
print (" 3. Dairy Milk:", dict["DairyMilk"])
print (" 4. Walkers Crisps:", dict["Walkers Crisps"])
snack = 1 # need a while loop, ignore
fb = 0.00
balance()
print("Your full balance is",fb)
【问题讨论】:
-
这叫做验证。使用循环检查输入是否在列表中。
-
如果你在处理金钱,你应该使用十进制库stackoverflow.com/a/32533307/2141635
标签: python python-3.x