我正试图使用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中的字符串比较,请单击此处
但是你可以试试这个代码:
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()
会将任何大写字母转换为小写字母,这样就可以减少的错误