break and continue in Python

break and continue in Python

The normal for syntax:

>>> for w in range(1,6):
     print(w)

1
2
3
4
5

All numbers has been printed.

With continue:

>>> for w in range(1,6):
     if w == 4:
…             continue
     print(w)

1
2
3
5

4 has been skipped, and then continued to the end.

With break:
>>> for w in range(1,6):
…     if w == 4:
…             break
     print(w)

1
2
3
>>>

At 4 for has been interrupted.

Leave a comment