Python:if(user_input)在字典中

时间:2017-07-25 13:39:20

标签: python dictionary if-statement

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

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

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

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

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

如何让程序打印"完成"?

2 个答案:

答案 0 :(得分:-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')

答案 1 :(得分:-4)

而不是> dput(iris[1:5,]) structure(list(Sepal.Length = c(5.1, 4.9, 4.7, 4.6, 5), Sepal.Width = c(3.5, 3, 3.2, 3.1, 3.6), Petal.Length = c(1.4, 1.4, 1.3, 1.5, 1.4), Petal.Width = c(0.2, 0.2, 0.2, 0.2, 0.2), Species = structure(c(1L, 1L, 1L, 1L, 1L), .Label = c("setosa", "versicolor", "virginica" ), class = "factor")), .Names = c("Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width", "Species"), row.names = c(NA, 5L), class = "data.frame") ,请使用input()

raw_input

<强>说明: Python 2 中,user_choice = raw_input('What would you like to buy? ') if user_choice in shop_inventory: print('Complete') else: print('Fail') 返回一个字符串,raw_input()尝试将输入作为Python表达式运行。

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

As statet here