Python 2.7:能否用多个raw_input行和一个while循环来处理输入错误?

2024-10-02 18:14:55 发布

您现在位置:Python中文网/ 问答频道 /正文

如果您有一个while循环,其中包含两个原始输入行,您希望每个原始输入行都重复,直到提供正确的输入,并且希望循环继续,直到获得特定的结果;这在Python中甚至可以不使用goto选项吗?你知道吗

#For example:
while True:
    a = raw_input("What is your name?: ")
    #Hypothetically assuming "Sam" is the only acceptable answer
    if a not in ["Sam"]:
        print "Error, try again."
    else:
        b = raw_input("How old are you?: ")
        #Hypothetically assuming 28 is the only acceptable answer
        if b not in [28]:
            print "Error, try again."
        else:
            continue
            #no break out of loop provided, this is just a quick hypothetical 

这是一个很快的例子(不是最好的……),但它只是给我的代码做什么的要点(完全初学者在这里)。如您所见,第一个错误的结果会很好,就像循环回到开始和第一个原始输入行一样,但是第二个原始输入行上的错误也会回到第一个原始输入行(有没有办法在while循环中间重复第二个原始输入行的位置?)如果可能的话,我想尝试修复我的代码,所以如果有任何方法可以使用这个非常长的while循环来工作,我将非常感谢您的意见。你知道吗


Tags: theanswerinonlyinputrawifis
2条回答

您可以使用一个变量来跟踪哪个问题到期,如下所示:

def ask(question, validator):
    a = input(question)
    return a if validator(a) else None

progress = 0
while progress < 2:
    if progress == 0:
        ok = a = ask("What is your name?: ", lambda a: a in ["Sam"])
    else:
        ok = b = ask("How old are you?: ", lambda b: b in [28])
    if ok == None:
        print ("Error, try again.")
    progress += int(ok != None)

备选方案

您可以将答案初始化为None,然后继续,直到最后一个答案不是None,同时询问仍然没有答案值的问题。你知道吗

如果答案验证失败,则可能引发异常:

def ask(question, validator):
    a = input(question)
    if not validator(a):
        raise ValueError
    return a 

progress = 0
a = None
b = None
while b == None:
    try:
        if a == None: a = ask("What is your name?: ", lambda x: x in ["Sam"]) 
        if b == None: b = ask("How old are you?: ", lambda x: x in [28])
    except ValueError:
        print ("Error, try again")

print (a, b)

一个优雅但不太先进的解决方案-

def ask_questions():
    yield "Sam" == raw_input("What is your name?: ")
    yield "28"  == raw_input("How old are you?: ")

while True:
    repeat = False

    for answer in ask_question():
        if not answer:
            repeat = True
            break

    if not repeat:
        break

相关问题 更多 >