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

Asked

Viewed 29,273 times

31

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

I have difficulties in English and I found that website that I can’t read.

So how can I use break, pass and continue to control Python script streams?

Have examples?

1 answer

44


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 to say, continues the natural flow of the cycle
  • pass: is to pass, I mean, let it 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 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 the continue:

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

The continue should continue the implementation of for, that when you find an item equal to four, you will go to the next iteration. And we receive 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 at the end of the list of commands of a cycle, since there is nothing else to do and the cycle will automatically pass to the next iteration.

Pass

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

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

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

  • 1

    pass is what some processors call NOOP =)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.