2017-07-25 19 views
0

在檢查用戶輸入是否在字典中有問題。Python:如果(user_input)在字典中

程序的基礎是有一個商店的庫存。這些項目被存儲在具有相應值的字典中,例如, {'kettle': 3,.....}

然後我希望用戶寫他們想要的東西。因此,如果用戶輸入'水壺',我想從商店庫存中移除商品並放入用戶庫存。

現在的主要問題是一起得到一個if語句。這是我想要的:

user_choice = input('What would you like to buy? ') 
if user_choice in shop_inventory: 
    print('Complete') 
else: 
    print('Fail') 

我怎樣才能讓程序打印「完整」?

+4

這段代碼有什麼問題?如果字典中包含'壺',並且用戶輸入該值,則這將打印'完成'。 –

+0

此代碼的工作原理 –

+1

在py2下,您必須使用'raw_input',而不是'input',因爲'input'會將輸入的數據評估爲python代碼。所以你必須用單引號輸入「水壺」。 – MatsLindh

回答

-4

代替input(),使用raw_input

user_choice = raw_input('What would you like to buy? ') 
if user_choice in shop_inventory: 
    print('Complete') 
else: 
    print('Fail') 

說明:的Python 2raw_input()返回字符串,和input()試圖運行輸入作爲Python表達式。

Python 3只有raw_input()。它已更名爲input()。你

As statet here

+0

什麼是逗號? – Kevin

+0

報價。編輯它.. @凱文 – BrutalGames

0

部分的問題是問如果在字典中,你想從清單中移除。我相信你可以使用「刪除」

user_choice = input('What would you like to buy? ') 
if user_choice in shop_inventory: 
    del shop_inventory[user_choice] 
    print(shop_inventory) 
    print('complete') 
else: 
    print('Fail') 
0

您可以使用pop()shop_inventory刪除該項目。

shop_inventory = {'kettle': 3} 
user_choice = input('What would you like to buy? ') 
if user_choice in shop_inventory: 
    shop_inventory.pop(user_choice) 
    print(shop_inventory) 
    print('Complete') 
else: 
    print('Fail')