TransWikia.com

My check for an input in a list is not working properly

Stack Overflow Asked on December 2, 2021

So I am trying to check whether or not an input is an item in a 2d array but the check is not working properly and is returning false for any input.

CODE:

menu = [["Cheese Pizza", 8], ["Pepperoni Pizza", 10], ["Meat Lovers Pizza", 12], ["Garlic Bread", 5], ["Chicken Wings", 6]]

write("How many unique items would you like to order? n")
itemno = int(input().strip())
for i in range(itemno):
    write("What item would you like to order? n")
    for k, (item, price) in enumerate(menu):
        write("{} n".format(item))
    while item not in menu:
        item = str(input().title())
        if item not in menu:
            write("Sorry this item does not seem to be available on the menu. n")

EXAMPLE:

enter image description here

EDIT: For those of you wondering write is a self defined command just to make the text print out in a cool way.

One Answer

To achieve the check using the in clause, you will have to specify the whole list

>>> menu = [["Cheese Pizza", 8], ["Pepperoni Pizza", 10], ["Meat Lovers Pizza", 12], ["Garlic Bread", 5], ["Chicken Wings", 6]]
>>> "Cheese Pizza" in menu
False
>>> ["Cheese Pizza", 8] in menu
True

For your particular usecase, I would suggest moving the menu to a dict rather than using it as a 2d list

menu = {
    "Cheese Pizza" : 8,
    "Pepperoni Pizza" : 10,
    "Meat Lovers Pizza" : 12,
    "Garlic Bread" : 5,
    "Chicken Wings" : 6
}
print("How many unique items would you like to order? n")
itemno = int(input().strip())
for i in range(itemno):
    print("What item would you like to order? n")
    for item, price in menu.items():
        print("{} n".format(item))
    item_input=""
    while item_input not in menu:
        item_input = str(input().title())
        if item_input not in menu:
            print("Sorry this item does not seem to be available on the menu. n")

Answered by kartikkillawala on December 2, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP