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

标签 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++ 中的格式正确。我只是不知道如何在此处显示正确的格式。 我敢肯定那里已经有类似的东西了,但我就是找不到。

最佳答案

您可以简单地使用 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' 的两个实例。那不是汽车品牌。您应该在其他地方处理行格式。

关于python - 检查选择并与 python 列表进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31353387/

相关文章:

python - 如何读取Python 2.7.6中特定行中的特定字符?

python - 在 Python 中比较随机结果并将其转换为 JSON 文件上的 "points"的简单方法

python - 通过 PyQt 中 QTableView 和 QTableWidget 的上下文菜单传递实例

python - python中的子进程错误

python - 如何使用 seaborn 绘制成对直方图

python-2.7 - 在python qt中带有线程的Qwebview

linux - Python 脚本输出参数模板

python - 仅从文件中获取新行

python - 带有透明图像的可拖动 Tkinter 标签仍然覆盖父 Canvas 中的图像

python - 从 SOAP 响应中解析多个值