2015-10-02 20 views
0

我需要編寫一個自動售貨機,只接受某些硬幣你如何只允許列表中的輸入? (蟒蛇自動售貨機)

「它可以讓你輸入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) 
+0

它被稱爲驗證。使用循環來檢查輸入是否在列表中。 –

+0

如果你正在處理的錢,你應該使用十進制數http://stackoverflow.com/a/32533307/2141635 –

回答

1

我建議轉換英鎊便士,所以你不必做浮動數學運算,只要你顯示數值就轉換回來,你也可以使用decimal這個模塊,b讓我們不要太參與到這一點。您的最終問題似乎是您正在比較不同類型的值,並且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 
+0

不妨使用一套硬幣 –

+0

@PadraicCunningham是的,只是不想拋出任何新的東西他們還在試圖弄清楚他們已經學過的東西。 set([1,2,5,10,20,50,100])'(或'{1,2,5,10,20,50,100}')將是完美的數據類型,但我懷疑OP是否已經瞭解了它們 –

+0

不要太早了解效率;)我認爲設置是一個重要的事情,要了解它們通常是二次和線性運行時間之間的差異。 –