'while'循环出错后如何返回特定点

编程入门 行业动态 更新时间:2024-10-27 11:22:44
本文介绍了'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后出现错误时,程序进入开始.它从头开始,而不是从 y 或 z 开始.但是在 x 没有问题,所以程序应该从 y 或 z 开始提问,因为问题发生在 y 或 z.

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'循环出错后如何返回特定点

本文发布于:2023-07-11 11:59:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1093976.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!