首页 > 解决方案 > 要求输入直到确切的字符串是输入问题

问题描述

这是我的 Python 代码:

choice = (input("Are you signed up? (y/n) "))

print(choice)

while True:
    if choice != "y" or choice != "n":
        choice = (input("Are you signed up? (y/n) "))
        print(choice)
    else:
        break

我希望程序一直要求用户输入,直到他们输入“y”或“n”。问题是它从不接受输入,即使他们确实输入了“y”或“n”。

当我打印他们输入的内容(这是一个真实的单词)时,它说它是“y”或“n”,但它仍然不接受它。

我已经使用 Python 有一段时间了,今天我只是在尝试一些东西,但由于某种原因我无法弄清楚,我觉得这很简单明了,但我很愚蠢地注意到它。

有人可以向我解释一下吗?谢谢你。

标签: pythonpython-3.x

解决方案


You need and instead of or in this case.

    if choice != "y" and choice != "n":

or if you prefer you can do

    if not (choice == "y" or choice == "n"):

You can also do:

    if choice not in ("y", "n"):    # THIS ONE IS PROBABLY THE BEST

or because these are each 1-character you can do:

    if choice not in "yn":

You can also do:

    if choice not in "Randy!" or choice in "Rad!":

推荐阅读