我想为此添加一个循环:
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/"
因此,如果用户输入任何其他内容,则会显示错误并将其发送回问题。
答案 0 :(得分: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/"
答案 1 :(得分: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