繁体   English   中英

如果循环在Python中停止,则仅运行一次语句

[英]Run statment only once if loop stops in Python

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

我需要这样的东西:

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构造的反向构造。

编辑:我已经更改了与实际问题相关的代码。 对于这个错误,我感到非常抱歉。 被其他东西轰炸,并没有正确思考。

如果只需要在内部while中断时该语句运行一次,为什么不将其放在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>

添加一个布尔值,在代码执行一次后即可切换! 这样,您始终可以使事情循环发生一次。 另外,如果要再次运行外部循环,内部循环将再次开始,并且将再次中断,因此您确定只希望运行该行一次吗?

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

如果需要在while循环之后继续执行代码, 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 <>

此操作的Pythonic方法是在while循环中使用else。 这是应该做的。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM