python - 如何成功地要求用户在两个选项之间进行选择

标签 python

这里是新程序员

我试图要求用户在两个选项之间进行选择,但我就是做不到。

inp = int(input())
while inp != 1 or inp != 2:
    print("You must type 1 or 2")
    inp = int(input())
if inp == 1:
    print("hi")
if inp == 2:
    print("ok")
    quit()

即使我在最初询问时输入 1 或 2,它仍然会返回“您必须输入 1 或 2”

我的最终目标是,如果他们输入 1,则继续该计划,而如果他们选择 2,则将结束该计划。感谢您的帮助。

最佳答案

inp = input("Choose 1 or 2 ")
if inp == "1":
    print("You chose one")
    # whatevercodeyouwant_1()
elif inp == "2":
    print("You chose two")
    # whatevercodeyouwant_2()
else:
    print("You must choose between 1 or 2")

或者如果您希望他们留在这里直到他们选择 1 或 2:

def one_or_two():
    inp = input("Choose 1 or 2")
    if inp == "1":
        print("You chose one")
        # whatevercodeyouwant_1()
    elif inp == "2":
        print("You chose two")
        # whatevercodeyouwant_2()
    else:
        print("You must choose between 1 or 2")
        return one_or_two()
one_or_two()

这可能不是最优雅的解决方案,但它是与“while”循环不同的方法。

关于python - 如何成功地要求用户在两个选项之间进行选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40569176/

相关文章:

python - 尝试调用 self 时出现扭曲错误

python - keras和scipy的2D卷积结果不同

python - 使用 Python 从电子邮件中提取文本

python - 比较两个数据帧列并输出第三个

python - Django / python : Generate random timezone respecting datetime within the next 24h

python - 使用 pandas get_loc 更有效的方法?

python - 403 错误代码 Google Drive Python 已超出此文件的下载配额

python - 使用 python 正则表达式匹配但不包括其中之一

python - 为什么在 Werkzeug 中绑定(bind)到上下文是必要的

python - 使用 jsonpath-ng 在 Python 中使用上下文更新 json 数据