【问题标题】:Add a loop until user inputs a valid answer? [closed]添加一个循环,直到用户输入一个有效的答案? [关闭]
【发布时间】:2012-11-28 19:07:32
【问题描述】:

我想为此添加一个循环:

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

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

【问题讨论】:

  • 您意识到如果用户输入的不是字母,他根本不会得到任何响应,对吧?这是你的意图吗?
  • 为什么如此严重的否决和关闭?这似乎是一个常见的初学者问题。

标签: python loops if-statement


【解决方案1】:

在顶部添加一个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/"

【讨论】:

  • 可能也想删除 and question.isalpha() 部分。
  • @martineau.. 是的,这实际上是不需要的。谢谢:)
  • 感谢大家的回复,我是新手编码员,也是该网站的新手,非常抱歉提出这个非常糟糕的问题:'(
  • @Molly.. 您可以通过单击旁边的箭头将此答案标记为已接受。
【解决方案2】:

类似这样的:

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

【讨论】:

    猜你喜欢
    • 2018-07-15
    • 2016-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-09
    相关资源
    最近更新 更多