如果您有一个while循环,其中包含两个原始输入行,您希望每个原始输入行都重复,直到提供正确的输入,并且希望循环继续,直到获得特定的结果;这在Python中甚至可以不使用goto选项吗?你知道吗
#For example:
while True:
a = raw_input("What is your name?: ")
#Hypothetically assuming "Sam" is the only acceptable answer
if a not in ["Sam"]:
print "Error, try again."
else:
b = raw_input("How old are you?: ")
#Hypothetically assuming 28 is the only acceptable answer
if b not in [28]:
print "Error, try again."
else:
continue
#no break out of loop provided, this is just a quick hypothetical
这是一个很快的例子(不是最好的……),但它只是给我的代码做什么的要点(完全初学者在这里)。如您所见,第一个错误的结果会很好,就像循环回到开始和第一个原始输入行一样,但是第二个原始输入行上的错误也会回到第一个原始输入行(有没有办法在while循环中间重复第二个原始输入行的位置?)如果可能的话,我想尝试修复我的代码,所以如果有任何方法可以使用这个非常长的while循环来工作,我将非常感谢您的意见。你知道吗
您可以使用一个变量来跟踪哪个问题到期,如下所示:
备选方案
您可以将答案初始化为
None
,然后继续,直到最后一个答案不是None
,同时询问仍然没有答案值的问题。你知道吗如果答案验证失败,则可能引发异常:
一个优雅但不太先进的解决方案-
相关问题 更多 >
编程相关推荐