首页 > 解决方案 > 循环直到正确输入

问题描述

我是 Python 新手,必须为学校项目编写此代码。

当用户说“否”时,意味着他们不是美国的,我希望程序退出。当用户没有输入任何内容时,我希望它说“请输入 y 或 n”并继续显示此消息,直到他们正确响应。

while location == "":
    location = input("Are you based in the US? Y/N ") 
    if location.upper().strip() == "Y" or location.upper().strip() == "YES":
        print("Great to know you're based here in the states")

    elif location.upper().strip() == "N" or location.upper().strip() == "NO": #when input is N or No display not eligible
        print("Sorry to be our supplier you must be based in the US!")
        quit() #stops program
    else:
        location = "" #if NZ based variable is not Y or N set NZ based variable to nothing
        print("Type Y or N") #displays to user To type Y or N

标签: pythonpython-3.x

解决方案


这里的基本思想是创建一个无限循环,只有在你得到你想要的输入时才打破它。正如您将要调用的那样upperstrip每次比较输入时,只要在获得输入时调用它们一次就足够了。

import sys

while True:
    location = input("Are you based in the US? Y/N ").upper().strip()

    if location in {"Y", "YES"}:
        print("Great to know you're based here in the states")
        break
    elif location in {"N", "NO"}:
        print("Sorry, to be our supplier you must be based in the US!")
        sys.exit() # no need to `break` here as the program quits
    else:
        print("Type Y or N")

推荐阅读