Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

break for loop in Python [duplicate]

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
like image 981
MBZ Avatar asked Mar 05 '26 05:03

MBZ


1 Answers

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
like image 55
Raymond Hettinger Avatar answered Mar 07 '26 18:03

Raymond Hettinger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!