将商品添加到购物清单Python

时间:2018-11-09 12:49:12

标签: python

我正在学习Python,并试图列出购物清单 您可以在其中添加项目

首先,如果购物清单为空,它将要求您添加商品 如果没有,它将自动添加,它将询问您想要的位置 放置物品(索引)

但是我也试图使程序在某些条件下退出,例如DONE 或“帮助”或“显示”,但即使我为此设置了条件,但仍无法正常工作,任何人都可以帮我解决这个问题

希望我解释得足够多

import os 
shopping_list =[]

# Function for clearing the screen 
def clear_screen():
    os.system("cls" if os.name == "nt" else "clear")

def show_help():
    print("Enter 'Done' if you finish adding item \n Enter 'Show' to show your items \n Enter 'Help' toshow this help ")

# Function to show the items that you've entered to the list
def show_item():
    clear_screen()
    index = 1
    for item in shopping_list:
        print("{} {}.".format(index,item))
        index += 1

# Function to add items to the list    
def add_to_list():
    while True:
        new_item = input("Please enter the item that you would like to add to your shopping list ")
        if shopping_list and ((new_item.upper() != "DONE") or (new_item.upper() != "HELP") or (new_item.upper() != "SHOW")):
            position = input("Where you would like to add {} to the list \n press 'Enter' if you want to add to the end of the list".format(new_item))
            position = abs(int(position))
            shopping_list.insert(position - 1 , new_item)
            show_item()
        else:

            if new_item.upper() == "DONE":
                break    
            elif new_item.upper() == "SHOW":
                show_item()
                continue
            elif new_item.upper() == "HELP":
                show_help()
                continue
            else:
                shopping_list.append(new_item)
            show_item()

show_help()
add_to_list()

1 个答案:

答案 0 :(得分:0)

欢迎来到stackoverflow。我认为您的逻辑陈述是错误的,您需要and而不是or。现在,您只需要使括号中的语句为真,就是new_item.upper()至少不是这三个词之一。它实际上不能等于False,因为三个中的两个始终为真。

((new_item.upper() != "DONE") or (new_item.upper() != "HELP") or (new_item.upper() != "SHOW"))

例如,如果您有done,则第一个语句为 False ,而其他两个语句为 True ,总计为 True 在或语句中。

>>> new_item = 'done'
>>> print((new_item.upper() != "DONE") or (new_item.upper() != "HELP") or (new_item.upper() != "SHOW"))
True