Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python, how to skip lines in a range loop

In python language, I want to skip lines of a range loop (or xrange) without breaking the loop, as illustrated below:

for i in range(10):
    ... some code happening
    ... some code happening

    if (some statement == True):
        skip the next lines of the loop, but do not break the loop until finished

    ... some code happening
    ... some code happening
like image 288
user3060854 Avatar asked Jul 04 '26 15:07

user3060854


2 Answers

Use continue

for i in range(10):
    if i == 5:
        continue
    print(i)

output:

 0
 1
 2
 3
 4
 6
 7
 8
 9
like image 112
57 revs, 41 users 26%LopDev Avatar answered Jul 09 '26 22:07

57 revs, 41 users 26%LopDev


You could just nest that block in a condition:

for i in range(10):
    ... some code happening
    ... some code happening

    if not some_statement:

        ... some code happening
        ... some code happening
like image 33
Mureinik Avatar answered Jul 09 '26 22:07

Mureinik



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!