我试图编写一个包含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
循环,还是有什么东西可以使它只在一个循环中工作?在
您误解了使用continue的方式,continue移动到循环的下一个迭代。要解决这个问题,只需删除continues
根据注释编辑:
我只使用
while True
值,因为我对您的系统一无所知利用
break
将帮助您实现您想要的我认为这里有两个非常简单、优雅的解决方案。在
我们的想法是有一系列问题要问。只要问题仍然存在,这两种实现都会继续询问。一种方法是使用
itertools.dropwhile()
方法从列表中删除元素,只要问题的答案是正确的,另一种方法会做一些不同的事情——见下文。在在这个示例实现中,神奇的答案“foo”是任何问题的错误答案。您可以在Python中运行它,以检查它是否会在您回答“foo”的问题上重新开始询问(剩余的)问题。在
通过修改
ask_question()
函数来适应您的情况应该很简单。在编辑 因此,在幕后,仍然有两个while循环(
takewhile()
是一个赠品:-)。只要有一点开箱即用的思想,它甚至可以不需要一个while循环就可以完成:递归就是这个词!在
^{pr2}$如果您愿意,可以压缩为:
[从生成器编辑到函数]
您可以尝试一个函数:
不确定您是否希望保留这些值,但如果您需要调整它,这应该会给您一些提示。在
结果:
^{pr2}$按注释编辑:
相关问题 更多 >
编程相关推荐