For Loop Not Breaking (Python)

后端 未结 8 776
春和景丽
春和景丽 2021-01-22 11:35

I\'m writing a simple For loop in Python. Is there a way to break the loop without using the \'break\' command. I would think that by setting count = 10 that the exit condition

8条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-22 12:28

    What @Rob Watts said: Python for loops don't work like Java or C for loops. To be a little more explicit...

    The C "equivalent" would be:

    for (count=0; count<5; count++) {
       /* do stuff */
       if (want_to_exit)
         count=10;
    }
    

    ... and this would work because the value of count gets checked (count<5) before the start of every iteration of the loop.

    In Python, range(5) creates a list [0, 1, 2, 3, 4] and then using for iterates over the elements of this list, copying them into the count variable one by one and handing them off to the loop body. The Python for loop doesn't "care" if you modify the loop variable in the body.

    Python's for loop is actually a lot more flexible than the C for loop because of this.

提交回复
热议问题