简体   繁体   English

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

[英]Using if statements with user inputs

I am trying to create a simple product inventory using python but for some reason the if statement won't run and I don't know what's wrong.我正在尝试使用 python 创建一个简单的产品库存,但由于某种原因if语句不会运行,我不知道出了什么问题。 Below is the output and inputs of the code.下面是 output 和代码输入。

#Code #代码

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()

#Output #输出

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

Process finished with exit code 0

Try this:尝试这个:

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()

If you want to know about comparing strings in python click here如果您想了解比较 python 中的字符串,请单击此处

but you can try this code:但你可以试试这段代码:

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()

So .lower() will convert any capital letter to small letters, so that errors can be reduced所以.lower()会将任何大写字母转换为小写字母,这样可以减少错误

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM