检查选择并与python列表进行比较

时间:2015-07-11 04:25:27

标签: python python-2.7

我要做的是检查用户的输入(使用raw_input)是否是全局列表中的有效选项。以下是我到目前为止所做的事情。

def car():
    print "You have selected the 'car' option.",
    print "Are you sure this is what you want?"
    car_sure = raw_input("Enter Yes or No: ").lower()

    if car_sure == "yes":
        car_brand_choice()

    elif car_sure == "no":
        print "You no longer want a car. Taking you back to select your vehicle type."
        type()

    else:
         dead("Not a valid option. You lose your vehicle purchasing opportunity.")

def car_brand_choice(): 
    print "These are the car brands I can provide to you."
    print "\n".join(car_brands)
    selection = raw_input("Now is your chance to pick which brand you want. ").title()
    print "You selected %s\n" %selection
    print "I have to verify your selection is valid.\n"

    if selection in car_brands:
        print "Valid selection. You may continue."

    else:
        print "Not valid selection."
        print "Go back and select a valid brand.\n"
        car_brand_choice()


start()

然后,验证将用于选择不同的有效品牌或允许用户继续使用当前品牌。 我希望,代码在Notepad ++中正确格式化。我只是不知道如何在这里显示正确的格式。 我确定已经有类似的东西,但我找不到它。

2 个答案:

答案 0 :(得分:1)

您可以简单地使用in运算符。

>>> 'BMW' in car_brands
True
>>> 'bmw' in car_brands
False

如您所见,它区分大小写。在您的情况下,您可以执行以下操作:

if selection.lower() in car_brands:
    print "Valid car brand."
else
    print "Invalid car brand."

另外,我会从'\n'删除car_brands的两个实例。那不是汽车品牌。您应该在其他地方处理行格式。

答案 1 :(得分:0)

好吧,好像你是初学者。

解决问题所需要的是in

selection = raw_input("Now is your chance to pick which brand you want. ")
print "You selected ", selection
if selection in car_brands:
    print "It is in the list"
else:
    print "Its not in the list"

car_brand_choice()中添加此内容。 如需进一步阅读,请查看docs