Python中的比较if语句

2024-06-21 20:36:19 发布

您现在位置:Python中文网/ 问答频道 /正文

from pip._vendor.distlib.compat import raw_input

Inventory1 = ["Rice", "Maze", "Oil", "Toothpaste", "Beans", "Cloth", "Pepper"]
print("Here are present items list information:", Inventory1)

CheckInv1 = input('Is this item present in the inventory: \n')

for CheckInv1 in Inventory1:
    if CheckInv1 == ("Rice", "Maze", "Oil", "Toothpaste", "Beans", "Cloth", "Pepper"):
        print("This item is present in the inventory list.")
        break
    else:
        print("User entered item is not present in the list.")
        break

问题:即使在代码输入中输入“Oil”文本,它仍然显示else print语句。 如果语句不进行比较。任何建议。谢谢


Tags: theininputitemlistprintoilrice
2条回答

很抱歉,此代码全部错误:

  1. 覆盖来自inputCheckInv1的值, 因为重复使用循环控制变量的相同名称

  2. 测试CheckInv1是否与值的元组相等,但 CheckInv1永远不会是一个元组,所以等式不是 可能的

  3. 您将break放在if的两个分支中,因此无论 if条件是否为真,循环将在第一个条件后结束 迭代

你真正需要做的很简单:

Inventory1 = ["Rice", "Maze", "Oil", "Toothpaste", "Beans", "Cloth", "Pepper"]
print("Here are present items list information:", Inventory1)

CheckInv1 = input('Is this item present in the inventory: \n')

if CheckInv1 in Inventory1:
    print("This item is present in the inventory list.")
else:
    print("User entered item is not present in the list.")

您正在尝试将项与元组进行比较。这是不同的类型,因此如果总是被评估为false

if CheckInv1 in ("Rice", "Maze", "Oil", "Toothpaste", "Beans", "Cloth", "Pepper"):

将检查CheckInv1内的内容是否是元组的元素

另外,请注意,您忽略了输入。内部for循环(for CheckInv1 in Inventory1:CheckInv1是前面定义的Invenory1的一项,而不是用户输入

若您的目的是检查用户输入是否在清单中,那个么应该删除for循环。如果要执行多次,请使用标志(如布尔值)保持循环,只要它的计算结果为true,并要求用户在循环中输入另一个输入:

from pip._vendor.distlib.compat import raw_input

Inventory1 = ["Rice", "Maze", "Oil", "Toothpaste", "Beans", "Cloth", "Pepper"]
print("Here are present items list information:", Inventory1)

CheckInv1 = input('Is this item present in the inventory: \n')
conLoop = True
while conLoop:
    if CheckInv1 in Inventory1:
        print("This item is present in the inventory list.")
        conLoop = False
    else:
        print("User entered item is not present in the list.")
        CheckInv1 = input('Is this item present in the inventory: \n')

此代码不断请求用户输入,直到其中一种产品进入库存

相关问题 更多 >