Skip to main content
 首页 » 编程设计

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

2025年05月04日9exmyth

我想做的是检查用户的输入(使用 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++ 中的格式正确。我只是不知道如何在此处显示正确的格式。 我敢肯定那里已经有类似的东西了,但我就是找不到。

请您参考如下方法:

您可以简单地使用 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." 

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