3

is it possible to break a for loop in Python, without break command?
I'm asking this question in order to compare it with C++ for loop, in which actually checks a condition each time.

i.e. it's possible to break a for loop in C++ like below:

for(int i=0; i<100; i++)
    i = 1000; // equal to break;

is it possible to do the same in Python?

for i in range(0,100):
    i = 10000 // not working
MBZ
  • 26,084
  • 47
  • 114
  • 191

5 Answers5

7

Python's for is really a "for each" and is used with iterables, not loop conditions.

Instead, use a while statement, which checks the loop condition on each pass:

i = 0
while i < 1000:
    i = 1000

Or use an if statement paired with a break statement to exit the loop:

for i in range(1000):
    if i == 10:
        break
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Raymond Hettinger
  • 216,523
  • 63
  • 388
  • 485
1

Use a while loop for that purpose:

i = 0
while i < 100:
    i = 1000
Sufian Latif
  • 13,086
  • 3
  • 33
  • 70
1

No, for doesn't work like that in Python. for iterates over a list (in this case) or other container or iterable. for i in range(0, 100) doesn't mean "increment i until i is greater than or equal to 100", it means "set i to successive items from a list of these 100 items until the list is exhausted."

If i is 50, then the next item of the list is still 51, regardless of what you may set i to.

break is better anyway.

kindall
  • 178,883
  • 35
  • 278
  • 309
0

This won't work (as you've noticed). The reason is that, in principle, you are iterating the elements of a list of ascending numbers (whether that is really true depends on if you're using python 2 or 3). You can use the 'break' keyword to break out of a loop at any time, although using it in excess might make it hard to follow your code.

FatalError
  • 52,695
  • 14
  • 99
  • 116
0

You might have to settle for the break statement:

http://docs.python.org/tutorial/controlflow.html

for i in range(0,100):
    print i
    if i == 10:
        break
Andy Arismendi
  • 50,577
  • 16
  • 107
  • 124