Python 中包含空列表的基本购物车

Basic shopping cart with empty list in Python

我似乎无法使这个基本代码正常工作? 我试图让人们从可用列表中的给定项目中进行选择,检查 userInput == available_items,将它们附加到我的空列表并允许用户继续、退出和打印他们的项目。 感谢您的帮助!

available_items = ['Yogurt', 'Hummus', 'Bananas', 'Stawberries', 'Crackers', 'Veggie Pack', 'Shaving Cream', 'Razors', 'Deodorant' ]
userItems=[]
shopping_1st = True
while shopping_1st:
    userInput = input("Hello valued guest! Choose from the selection of available items to be added to your cart. ")
    response = input("'y' = Continue shopping?  'n' = continue to cart ")
    if str.lower(response) == 'n':
       shopping_1st = False
    elif str.upper(userInput) != available_items:
       print("Item not available:")
       print("Select from available items:")
    else:
        userItems.append(str.lower(userInput))
    for userInput in userItems:
        print(userInput)

您有多个问题:

  1. str.upper(userInput) != available_items 将尝试将字符串与列表进行比较,这将始终 return False.
  2. .upper 将所有字母转换为大写。考虑使用 .title().

尝试

...
elif userInput.title() not in available_items:
...

试试下面的代码:

available_items = ['Yogurt', 'Hummus', 'Bananas', 'Stawberries', 'Crackers', 'Veggie Pack', 'Shaving Cream', 'Razors', 'Deodorant' ]
userItems=[]
shopping_1st = True

while shopping_1st:
    userInput = input("Hello valued guest! Choose from the selection of available items to be added to your cart. ")

    if str.capitalize(userInput) not in available_items:
        print("Item not available:")
        print("Select from available items:")
    else:
        userItems.append(str.lower(userInput))

    response = input("'y' = Continue shopping?  'n' = continue to cart ")
    if str.lower(response) == 'n':
       shopping_1st = False       

for userInput in userItems:
    print(userInput)