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

15

The Python documentation in Portuguese is a work in progress, and fairly confusing how can you see .

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

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

Are there any examples?

    
asked by anonymous 13.12.2013 / 17:06

1 answer

26

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, the natural flow of the cycle continues
  • pass : is to pass, that is, lets pass.

These things get clearer with an example:

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

When we print the list, we get:

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

Let's then test our flow control commands:

Break

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

The break should break the execution of 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 execution of for , which when it finds an item equal to four, will move 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 does not make sense to put a continue at the end of the list of commands in a cycle, since there is nothing else to do and the cycle will automatically move to the next iteration.

Pass

The pass is a word that must be used whenever the program requests a syntactic filling of a gap, such as defining 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 code above ensures that even if I am not sure about the function, it can exist and be used in the rest of my code, without error.

    
13.12.2013 / 17:06