当前位置:   article > 正文

python中outside loop_Python: 'break' outside loop

python中outside loop_Python: 'break' outside loop

可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):

问题:

in the following python code: narg=len(sys.argv) print "@length arg= ", narg if narg == 1: print "@Usage: input_filename nelements nintervals" break

I get: SyntaxError: 'break' outside loop

Why?

回答1:

Because break cannot be used to break out of an if - it can only break out of loops. That's the way Python (and most other languages) are specified to behave.

What are you trying to do? Perhaps you should use sys.exit() or return instead?

回答2:

Because the break statement is intended to break out of loops. You don't need to break out of an if statement - it just ends at the end.

回答3:

Because break can only be used inside a loop. It is used to break out of a loop (stop the loop).

回答4:

break breaks out of a loop, not an if statement, as others have pointed out. The motivation for this isn't too hard to see; think about code like for item in some_iterable: ... if break_condition(): break

The break would be pretty useless if it finished the if block rather than breaking the loop. Consider that I cannot think of a case that you'd use break any way but inside an if statement to break the loop the if statement is in.

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/909216
推荐阅读
相关标签
  

闽ICP备14008679号