For Loop Not Breaking (Python)

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

    For loops in Python work like this.

    You have an iterable object (such as a list or a tuple) and then you look at each element in the iterable, storing the current value in a specified variable

    That is why

    for i in [0, 1, 2, 3]:
        print item
    

    and

    for j in range(4):
        print alist[j]
    

    work exactly the same. i and j are your storage variables while [0, 1, 2, 3] and range(4) are your respective iterables. range(4) returns the list [0, 1, 2, 3] making it identical to the first example.

    In your example you try to assign your storage variable count to some new number (which would work in some languages). In python however count would just be reassigned to the next variable in the range and continue on. If you want to break out of a loop

    1. Use break. This is the most pythonic way
    2. Make a function and return a value in the middle (I'm not sure if this is what you'd want to do with your specific program)
    3. Use a try/except block and raise an Exception although this would be inappropriate

    As a side note, you may want to consider using xrange() if you'll always/often be breaking out of your list early.

    The advantage of xrange() over range() is minimal ... except when ... all of the range’s elements are never used (such as when the loop is usually terminated with break)

    As pointed out in the comments below, xrange only applies in python 2.x. In python 3 all ranges function like xrange

提交回复
热议问题