我需要編寫一個自動售貨機,只接受某些硬幣你如何只允許列表中的輸入? (蟒蛇自動售貨機)
「它可以讓你輸入1P,2P,5P,10便士,20便士,50便士和£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? 我認爲這意味着我需要改變我的浮動(輸入())和一切浮動爲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)
它被稱爲驗證。使用循環來檢查輸入是否在列表中。 –
如果你正在處理的錢,你應該使用十進制數http://stackoverflow.com/a/32533307/2141635 –