gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 17:26:11 29 4
gpt4 key购买 nike

我正在尝试编写一个包含 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..

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

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

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

最佳答案

[从生成器编辑到函数]

你可以试试一个函数:

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

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

结果:

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

关于python - 'while'循环出错后如何返回特定点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32961271/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com