Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/358.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将if语句与用户输入一起使用_Python_If Statement_User Input - Fatal编程技术网

Python 将if语句与用户输入一起使用

Python 将if语句与用户输入一起使用,python,if-statement,user-input,Python,If Statement,User Input,我试图使用python创建一个简单的产品清单,但由于某种原因,if语句无法运行,我不知道出了什么问题。下面是代码的输出和输入 #代码 def inventory_products(): choice=str(输入(“您想做什么?\n输入添加项目、数量、显示库存:”) 如果选项==“添加项目”: 输入(“输入名称”) 库存产品() #输出 您想做什么? 输入添加项目、数量、显示库存:添加项目 进程已完成,退出代码为0 试试这个: def inventory_products(): cho

我试图使用python创建一个简单的产品清单,但由于某种原因,
if
语句无法运行,我不知道出了什么问题。下面是代码的输出和输入

#代码

def inventory_products():
choice=str(输入(“您想做什么?\n输入添加项目、数量、显示库存:”)
如果选项==“添加项目”:
输入(“输入名称”)
库存产品()
#输出

您想做什么?
输入添加项目、数量、显示库存:添加项目
进程已完成,退出代码为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中字符串的比较,请单击

但您可以尝试以下代码:

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()
会将任何大写字母转换为小写字母,这样可以减少错误

看起来您在项目后面有额外的空间,而且
input()
周围的
str()
是多余的,因为
input()
总是返回字符串。@Tuqay不确定,但可能是因为你可以突出它:p但是像。。。问这样一个问题而不至少运行一次代码是一个巨大的问题,所以
if
对我来说很有用。我可以看到
输入名称
,我必须输入一些内容才能结束程序。我必须在第一个
input()
处准确输入
additem
,它才能工作。此代码应该可以工作。看起来您不小心在答案末尾添加了一个空格,因此输入与
添加项
不完全相同。非常感谢!!非常感谢你!!