Python 在搜索中,当期望为真时给出假
我正在尝试运行下面的Python,并期望最后一项被证明是正确的。我正在寻找啤酒,看看它是否存在于菜单中,但我得到的是错误的。我错过了什么Python 在搜索中,当期望为真时给出假,python,python-3.x,Python,Python 3.x,我正在尝试运行下面的Python,并期望最后一项被证明是正确的。我正在寻找啤酒,看看它是否存在于菜单中,但我得到的是错误的。我错过了什么 # [] print 3 tests, with description text, testing the menu variable for 'pizza', 'soup' and 'dessert' menu = "salad, pasta, sandwich, pizza, drinks, dessert, soda, beer" print("piz
# [] print 3 tests, with description text, testing the menu variable for 'pizza', 'soup' and 'dessert'
menu = "salad, pasta, sandwich, pizza, drinks, dessert, soda, beer"
print("pizza is in the menu =", 'pizza' in menu)
print("soup is in the menu =", 'soup' in menu)
print("dessert is in the menu = ", 'dessert' in menu)
print("beer is in the menue = ", 'beer' in menu)
#now asking for a user to search an item
menu_ask = input("Type an item to see if it is in the menu: ")
print(menu_ask,"is in the menu = ", 'menu_ask'.lower() in menu.lower())
我的输出如下
pizza is in the menu = True
soup is in the menu = False
dessert is in the menu = True
beer is in the menue = True
Type an item to see if it is in the menu: beer
beer is in the menu = False
为什么最后一项不正确?我怎样才能让它成为真的呢
print(menu_ask,"is in the menu = ", 'menu_ask'.lower() in menu.lower())
不接受变量menu\u ask,而是接受字符串“menu\u ask”,该字符串不在menu中
将其更改为:
print(menu_ask,"is in the menu = ", menu_ask.lower() in menu.lower())
它应该按预期的方式工作
'menu\u ask'。lower()
只是字符串'menu\u ask'
。去掉那些引语。我刚刚运行了你的代码,“--啤酒在菜单中”是真的只要用菜单询问.lower()
替换菜单询问.lower()
。换句话说,删除“菜单询问”的引号。你可以改进你的菜单。事实上,通过jasonharper的修正(以及Rafik和SuperKeksmann的修正),它表明菜单上有沙子、蜜蜂和墨水。你应该使用列表或集合,而不是字符串,这样你就不会匹配部分单词。