For Loop Not Breaking (Python)

后端 未结 8 758
春和景丽
春和景丽 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:11

    The for loop that you have here is not quite the same as what you see in other programming languages such as Java and C. range(0,5) generates a list, and the for loop iterates through it. There is no condition being checked at each iteration of the loop. Thus, you can reassign the loop variable to your heart's desire, but at the next iteration it will simply be set to whatever value comes next in the list.

    It really wouldn't make sense for this to work anyway, as you can iterate through an arbitrary list. What if your list was, instead of range(0,5), something like [1, 3, -77, 'Word', 12, 'Hello']? There would be no way to reassign the variable in a way that makes sense for breaking the loop.

    I can think of three reasonable ways to break from the loop:

    1. Use the break statement. This keeps your code clean and easy to understand
    2. Surround the loop in a try-except block and raise an exception. This would not be appropriate for the example you've shown here, but it is a way that you can break out of one (or more!) for loops.
    3. Put the code into a function and use a return statement to break out. This also allows you to break out of more than one for loop.

    One additional way (at least in Python 2.7) that you can break from the loop is to use an existing list and then modify it during iteration. Note that this is a very bad way to it, but it works. I'm not sure that this will this example will work in Python 3.x, but it works in Python 2.7:

    iterlist = [1,2,3,4]
    for i in iterlist:
        doSomething(i)
        if i == 2:
            iterlist[:] = []
    

    If you have doSomething print out i, it will only print out 1 and 2, then exits the loop with no error. Again, this is a bad way to do it.

提交回复
热议问题