Python:if(user_input)在字典中

问题描述 投票:-1回答:2

检查用户输入是否在字典中时遇到问题。

程序的基础是商店库存。这些项目存储在具有相应值的字典中,例如{'kettle': 3,.....}

然后我希望用户写下他们想要的东西。因此,如果用户输入了“水壶”,我想从商店库存中删除该商品并放入用户库存。

现在的主要问题是将if语句放在一起。这就是我正在尝试的:

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

如何让程序打印“完成”?

python dictionary if-statement
2个回答
-1
投票

您可以使用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')

-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 2中,raw_input()返回一个字符串,input()尝试将输入作为Python表达式运行。

在Python 3中只有raw_input()。它在input()重新命名。

As statet here

© www.soinside.com 2019 - 2024. All rights reserved.