循环直到正确输入

时间:2018-08-20 07:12:43

标签: python python-3.x

我是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

1 个答案:

答案 0 :(得分:1)

这里的基本思想是创建一个无限循环,并仅在获得所需输入时才将其中断。由于每次比较输入时都会调用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")