-3

我想为此添加一个循环:

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/"

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

4

2 回答 2

6

在顶部添加一个 while 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/"
于 2012-11-28T19:09:01.633 回答
0

像这样的东西:

answer={"Y":"Reboot","N":"Reboot cancled"} #use a dictionary instead of if-else
inp=raw_input("Reboot Y/N: ")

while inp not in ('n','N','y','Y') :  #use a tuple to specify valid inputs
   print "invalid input"
   inp=raw_input("Reboot Y/N: ")

print answer[inp.upper()]   

输出:

$ python so27.py

Reboot Y/N: foo
invalid input
Reboot Y/N: bar
invalid input
Reboot Y/N: y
Reboot
于 2012-11-28T19:19:34.853 回答