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
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
break
. This is the most pythonic wayreturn
a value in the middle (I'm not sure if this is what you'd want to do with your specific program)try/except
block and raise an Exception
although this would be inappropriateAs 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 range
s function like xrange