添加一个循环,直到用户输入有效答案?

Mol*_*lly -2 python loops if-statement

我想为此添加一个循环:

question = raw_input("Reboot Y/N ")
if len(question) > 0 and question.isalpha():
    answer = question.upper()
    if answer == "Y":
        print "Reboot"
    elif answer == "N":
        print "Reboot Cancled"
    else:
        print "/ERROR/"
Run Code Online (Sandbox Code Playgroud)

因此,如果用户输入任何其他内容,则会出现错误并将其发送回问题.

Roh*_*ain 6

在顶部添加一个True,如果用户输入了正确的输出,则打破循环: -

while True:
    question = raw_input("Reboot Y/N ")
    if len(question) > 0:
        answer = question.upper()
        if answer == "Y":
            print "Reboot"
            break
        elif answer == "N":
            print "Reboot Canceled"
            break
        else:
            print "/ERROR/"
Run Code Online (Sandbox Code Playgroud)