我需要编码自动售货机,只接受某些硬币
“这将允许您输入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? 我认为这意味着我需要更改我的浮点数(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)
答案 0 :(得分:1)
我建议将磅转换为便士,这样您就不必进行浮动数学运算,只需在显示值时转换回来。您也可以使用decimal
模块,但是我们还没有太多参与其中。您的最终问题似乎是您正在比较不同类型的值,1 != "1"
。让我们先排序。
coins = [1, 2, 5, 10, 20, 50, 100] # pence
coin_in = int(input("Enter amount (in pence): "))
if coin_in not in coins:
# incorrect input, handle it