'while'循环出错后如何返回特定点 [英] How to return a specific point after an error in 'while' loop

查看:25
本文介绍了'while'循环出错后如何返回特定点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to write a program that include a while loop, in this loop I have an error message if something goes wrong. It's kinda like this;

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..

问题如下:questionX后出现错误时,程序进入开始.它从头开始,而不是从 yz 开始.但是在 x 没有问题,所以程序应该从 yz 开始提问,因为问题发生在 yz.

The problem is as follows: when an error occurs after questionX, the program goes to beginning. It starts from the beginning, not from y or z. But at x there is no problem, so that, the program should start asking questions from y or z because, the problem occurred at y or z.

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

How can I make the program start from a specific point, like if there is an error only at yquestion, program must start asking questions from y or if only at z,program must start from z, not beginning-not x.

我是否应该为此使用多个 while 循环,或者是否有任何方法使此操作仅在一个循环中起作用?

Should I use more than one while loop for this or is there anything that makes this work only in one loop?

推荐答案

你可以尝试一个函数:

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

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

Not sure if you want to keep the values, but if you need to tweak it, this should give you hints.

结果:

Question about X?
"blah"
Something wrong with question Question about X?

Question about X?
"blah"
Something wrong with question Question about X?

Question about X?
"TrueX"
Question about Y?
"TrueY"
Question about Z?
"blah"
Something wrong with question Question about Z?

Question about Z?
"blah"
Something wrong with question Question about Z?

Question about Z?
"TrueZ"

按评论

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

这篇关于'while'循环出错后如何返回特定点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆