简体   繁体   English

Python 3 用例是 continue 而不是 not (!=)

[英]Python 3 Use case for continue instead of not (!=)

So I'm learning Python finally and I've just learned about skipping to the next iteration of a loop using continue.所以我终于学习了 Python,我刚刚学会了使用 continue 跳到循环的下一次迭代。 Now my question is, what would be a real world use case for continue instead of not or != ?现在我的问题是, continue 而不是 not 或 != 的真实世界用例是什么?

Consider the three pieces of simple code below:考虑下面的三段简单代码:

for i in range(0, 10):
    if i == 3:
        continue
    print(i)

for i in range(0, 10):
    if i != 3:
        print(i)

for i in range(0, 10):
    if i == 3:
        log()
    print(i)

In my mind, I don't see why I should prefer the first to the second.在我看来,我不明白为什么我应该更喜欢第一个而不是第二个。 I found another question regarding continue, and someone mentioned about using it when they wanted to log something, but in that case, why not use the third example?我发现了另一个关于 continue 的问题,有人提到在他们想记录某些东西时使用它,但在这种情况下,为什么不使用第三个示例?

I fully understand that for such a simple example as I've given, the difference probably isn't much but could someone tell me when I should prefer continue?我完全理解,对于我给出的这样一个简单的例子,差别可能不大,但有人能告诉我什么时候应该继续吗? Or is it just more of a "avoiding the use of !=" case?或者它更像是“避免使用 != 的情况?

continue for a loop is just like return to a function: a convenience instruction to skip to the next iteration right now . continue for a loop 就像return到一个函数:一个方便的指令现在跳到下一次迭代。

On a complex case, continue can skip to the next iteration very simply:在复杂的情况下, continue可以非常简单地跳到下一次迭代:

for i in range(0, 10):
    if i != 3:
        print("something")
        if my_function(i) != 34:
           continue
    print(i)

To do that without continue , you need a flag or else conditions.要在没有continue情况下做到这一点,您需要一个标志或else条件。 Careful as if there are a lot of continue statements in your loops it can become difficult to debug (just like when you put too many return statements in a function)小心,好像循环中有很多continue语句可能会变得难以调试(就像在函数中放入太多return语句一样)

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

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