使用带有用户输入的 if 语句

Using if statements with user inputs

我正在尝试使用 python 创建一个简单的产品库存,但由于某些原因,if 语句不会 运行 而且我不知道出了什么问题。下面是代码的输出和输入。

#代码

def inventory_products():
    choice = str(input("What do you want to do? \nEnter Add item, Quantity, Show Inventory:"))
    if choice == 'Add item':
        input("Enter name")
inventory_products()

#输出

What do you want to do? 
Enter Add item, Quantity, Show Inventory:Add item 

Process finished with exit code 0

试试这个:

def inventory_products():
    choice = str(input("What do you want to do? \nEnter Add item, Quantity, Show Inventory:"))
    if choice.strip() == 'Add item': # change in code to remove extra spaces
        input("Enter name")
inventory_products()

如果您想了解 python 中的字符串比较,请单击 here

但你可以试试这个代码:

def inventory_products():
    choice = str(input("What do you want to do? \nEnter Add item, Quantity, Show Inventory:")).lower()
    if choice.strip() == 'add item':
        input("Enter name: ")
    else:
        print("Invalid Choice!")

inventory_products()

所以.lower()会将任何大写字母转换为小写字母,这样可以减少错误