首页 > 解决方案 > 处理代码以查看输入的汽车模型是否存在于提供的集合中......但是只有 else 阻止工作

问题描述

即使提供的值在列表中,for 循环仍在工作

尝试在不同的 IDE 中运行代码。但是代码在这些环境中都不起作用

#Check whether the given car is in stock in showroom
carsInShowroom = ["baleno", "swift", "wagonr", "800", "s-cross", "alto", "dezire", "ciaz"]

print("Please enter a car of your choice sir:")

carCustomer = input()

carWanted = carCustomer.lower()

for i in carsInShowroom:
    if i is carWanted:
        print("Sir we do have the Car")
        break
else:
    print("Sorry Sir we do not currently have that model")

只有 else 会阻止运行。当我输入时wagonr,输出显示“对不起先生,我们目前没有那个模型”

标签: python-3.x

解决方案


改变这个,

if i is carWanted: # `is` will return True, if 

if i == carWanted.strip(): # strip for remove spaces

为什么?

  • is是为了参考平等。
  • ==是为了价值平等。

*注意:wagonr您的输入不 应该是wagon r


推荐阅读