如何在“while”循环中发生错误后返回特定点

2024-10-01 07:46:18 发布

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

我试图编写一个包含while循环的程序,在这个循环中,如果出了问题,我会收到一条错误消息。有点像这样

while True:

    questionx = input("....")
    if x =="SomethingWrongabout questionX":
        print ("Something went wrong.")
        continue
    other codes...

    questiony = input("....")
    if y == "SomethingWrongabout questionY":
        print ("Something went wrong.")
        continue

    other codes...

    questionz = input("....")
    if z == "SomethingWrongabout questionZ":
       print ("Something went wrong.")
       continue

    other codes..

{{2>在程序开始后}出现错误。它从开头开始,而不是y或{}。但是在x没有问题,所以程序应该从y或{}开始提问,因为问题发生在y或{}。在

我怎样才能使程序从一个特定的点开始,比如如果只有在y问题上有错误,程序必须从y开始提问,或者如果只在z开始,程序必须从z开始,而不是x。在

我应该为此使用多个while循环,还是有什么东西可以使它只在一个循环中工作?在


Tags: 程序消息inputif错误somethingcodesother
3条回答

您误解了使用continue的方式,continue移动到循环的下一个迭代。要解决这个问题,只需删除continues

根据注释编辑:

我只使用while True值,因为我对您的系统一无所知

while True:
    while True:
        questionx = input("....")
        if x =="SomethingWrongabout questionX":
            print ("Something went wrong.")
            continue
        else:
            break;

利用break将帮助您实现您想要的

我认为这里有两个非常简单、优雅的解决方案。在

我们的想法是有一系列问题要问。只要问题仍然存在,这两种实现都会继续询问。一种方法是使用itertools.dropwhile()方法从列表中删除元素,只要问题的答案是正确的,另一种方法会做一些不同的事情——见下文。在

在这个示例实现中,神奇的答案“foo”是任何问题的错误答案。您可以在Python中运行它,以检查它是否会在您回答“foo”的问题上重新开始询问(剩余的)问题。在

通过修改ask_question()函数来适应您的情况应该很简单。在

import itertools

input = lambda x: raw_input("what is your "+x+"? ")

# returns true or false; wether or not the question was answered 
# correctly
def ask_question(question):
    answer = input(question)
    # could be any test involving answer
    return answer != "foo"

# assume we have a list of questions to ask
questions = [ "age", "height", "dog's name" ]

# keep on looping until there are questions
while questions:
    questions = list(itertools.dropwhile(ask_question, questions))

编辑 因此,在幕后,仍然有两个while循环(takewhile()是一个赠品:-)。只要有一点开箱即用的思想,它甚至可以不需要一个while循环就可以完成:

递归就是这个词!在

^{pr2}$

如果您愿意,可以压缩为:

def ask(q_list):
    if qlist:
        ask(q_list[1:]) if ask_question(q_list[0]) else ask(q_list)

[从生成器编辑到函数]

您可以尝试一个函数:

def check_answer(question, answer):
    while True:
        current_answer = input(question)
        if current_answer == answer:
            break
        print "Something wrong with question {}".format(question)
    return current_answer

answerX = check_answer("Question about X?\n", "TrueX")
answerY = check_answer("Question about Y?\n", "TrueY")
answerZ = check_answer("Question about Z?\n", "TrueZ")

不确定您是否希望保留这些值,但如果您需要调整它,这应该会给您一些提示。在

结果:

^{pr2}$

按注释编辑:

def check_answer(question, answers):
    while True:
        current_answer = input(question)
        if current_answer in answers:
            break
        print "Something wrong with question {}".format(question)
    return current_answer

answerX = check_answer("Question about X?\n", ("TrueX", "TrueY")

相关问题 更多 >