是否可以使用多个raw_input行和一个while循环处理错误的输入 - Python 2.7

时间:2016-12-29 09:48:41

标签: python python-2.7

如果你有一个带有两个raw_input行的while循环,你需要重复每个raw_input行,直到提供了正确的输入,并且你还希望循环继续直到达到特定的结果;如果没有goto选项,这在Python中是否可行?

#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 

这是一个非常快速的例子(而不是最好的......),但它只是给出了我尝试用我的代码做的要点(这里是完整的初学者)。正如你所看到的,第一个错误会很好,因为事情会循环回到开头和第一个raw_input行,但是第二个raw_input行上的错误也会回到第一个raw_input行(有没有办法到在第二个raw_input行的while循环中间重复?)如果可能的话,我想尝试抢救我的代码,所以如果有任何方法可以使用这个非常长的循环来使事情工作,我会真的很感激你的意见。

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

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

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,同时询问仍然没有no-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)