What is the difference between break, pass and continue in Python?

The Python documentation in English is a work in progress, and reasonably confusing as you can see.

I have difficulties in English and found this site that I can not read.

So how can I use break, pass and continue to control program flows in Python?

Have examples?

Author: Vinicius Brasil, 2013-12-13

1 answers

If we translate the words, they give us a hint of what they actually do with the flow:

  • break: is to break, break (or interrupt) the natural flow of the program
  • continue: is to continue, that is, continues the natural flow of the cycle
  • pass: it is to pass, that is, let pass.

These things become clearer with an example:

numeros = list()
for i in xrange(10):
    numeros.append(i)

By printing the list, we get:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Let's then test our Flow Control:

Break

for item in numeros:
    if item >= 2:
        break
    print item

The break should break the execution of the for, and that's exactly what happens, we get the following result:

0
1

Continue

Now for continue:

for item in numeros:
    if item == 4:
        continue
    print item

The continue should continue the execution of the for, which when it finds an item equal to four, will move on to the next iteration. And we get the result without the 4:

0
1
2
3
5
6
7
8
9

As pointed out by @ MarcoAurelio, it makes no sense to put a continue to the end of a cycle's list of commands, as there is nothing else to do and the cycle will automatically move on to the next iteration.

Pass

pass is a word that should be used whenever the program syntactically requests that a gap be filled, as is the case with the definition of a function: after the line of def there must be some content.

def soma_de_quadrados(x, y):
    pass # k = x**x + y**y
    # return k

The above code ensures that even though I'm not sure about the function, it can exist and be used in the rest of my code, without presenting errors.

 41
Author: LuizAngioletti, 2013-12-30 12:47:04