2014-07-10 91 views
0

我一直在做一些事情,需要在另一个无限的while循环内运行一个无限的while循环(不要判断)并在发生某种事件时中断。我需要在内部循环中断时运行一次语句,而不必在外部循环中修改它。如果在Python中循环停止,只运行语句一次

我需要的是这样的:

while True: 
    while condition: 
     do stuff 
    <run some code when the inside while finishes> 

    continue running external loop without running the line inside <> 

基本上,while-else结构的反向。

编辑:我已经改变了代码来解决真正的问题。我很抱歉这个错误。被其他东西轰炸,并没有想好。

+5

为什么不在'break'之前移动''? – bereal

回答

3

如果你只需要语句在内部休息时运行一次,为什么不把它放在if块呢?

while True: 
    while condition: 
    if other-condition: 
     <code to run when the inside loop breaks> 
     break 

    <continue external loop> 

编辑:为了(无if other_condition: ...; break)只有一次内部循环完成后运行,你应该使用下列内容:

while True: 
    has_run = False 
    while condition: 
    <loop code> 
    if not has_run: 
    <code to run when inner loop finishes> 
    has_run = True 

    <rest of outer loop code> 
+0

因为我在写代码的时候搞乱了代码。抱歉。 – Dumitru

+0

@KuraiHikari这可能是我错误地解释了你的编辑,但似乎我提出的解决方案仍然有效。如果情况并非如此,请澄清。 – RevanProdigalKnight

+0

事情是,没有“如果”,也没有“其他条件”。我自己误解了这个问题,并错误地发布了它。如果我将''condition''而不是'other-condition'',基本上重复代码,你的代码就可以工作。 – Dumitru

-1

添加您切换代码已经经过布尔执行一次!通过这种方式,您可以始终在循环中让事情发生一次。另外,如果你想再次运行外部循环,内部循环将再次启动,并且会再次中断,那么你确定只想运行那一行吗?

broken = False 
while True: 
    while condition: 
     if other-condition: 
      break 
    if not broken: 
     broken = True 
     <run some code when the inside while breaks> 

    continue running external loop without running the line inside <> 
-1

如果需要继续后while循环代码要比使用可变was_break

while True: 

    was_break = False 

    while condition: 
     if other-condition: 
      was_break = True 
      break 

    if was_break: 
     <run some code when the inside while breaks> 

    continue running external loop without running the line inside <> 
+0

来自downvoter的评论? – furas

-1

Python的方式进行,这是与while循环使用别的。这是应该如何完成的。

如果else语句与while循环一起使用,则在条件变为false时执行else语句。

x=1 
while x: 
    print "in while" 
    x=0 
    #your code here 
else: 
    print "in else" 
+0

“while-else”的问题是每当'while'中的条件是'False'时''else''都会运行,所以这是一个禁止行为。当循环结束时,我需要该代码运行一次。 – Dumitru

+0

是的,这是真的。 –

+0

如果在'while'中执行'break',则'else'不执行 - OP需要相反的东西。 – furas