3

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
Mureinik
  • 297,002
  • 52
  • 306
  • 350
user3060854
  • 923
  • 2
  • 15
  • 25
  • 5
    Use `continue`. – meowgoesthedog Jan 19 '19 at 21:09
  • 3
    I would not recommend `continue`, you can always write better code without it. Do `if not expression: ` – cs95 Jan 19 '19 at 21:11
  • @coldspeed better in which form? – Vicrobot Jan 19 '19 at 21:19
  • `continue` is a synonym for a `goto` jumping to place just after the loop. For the explanation why `goto` is to be avoided I would refer to the famous ["Go To Statement Considered Harmful"](https://homepages.cwi.nl/~storm/teaching/reader/Dijkstra68.pdf) by Edgar Dijkstra. – sophros Jan 19 '19 at 21:36
  • @sophros Yet, how could continue be avoided if every line of the code inside the loop is depented to the previous line? – user3060854 Jan 19 '19 at 21:49
  • @user3060854 - for this reason you were suggested `if` statements structure in the answers below. And this is not the only way to structure you code... but it is beyond the comment to elaborate on this (e.g. [use dictionary](https://stackoverflow.com/questions/49881114/how-to-use-dictionary-instead-of-if-statement-in-python) ). – sophros Jan 20 '19 at 10:16

2 Answers2

4

Use continue

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

output:

 0
 1
 2
 3
 4
 6
 7
 8
 9
kajarenc
  • 103
  • 4
1

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
Mureinik
  • 297,002
  • 52
  • 306
  • 350