-4

In my code, the keywords 'continue' and 'break' give the same output. What is the reason?

First code:

x = 0
while x < 5:
    if x == 2:
        break
    print(x)
    x += 1

Output: 0 1

Second code:

x = 0
while x < 5:
    if x == 2:
        continue
    print(x)
    x += 1

Output: 0 1

In the 1st code, I expected the same output. And in the 2nd one, I expected the output to be like this: Output: 0 1 3 4

Röyal
  • 87
  • 9
  • 2
    I would suggest looking at what continue does, because I don't think it does what you think it does. – Chris Apr 24 '19 at 19:27
  • @brunns: You are right, the second one never terminates, but if you run this code in the interpreter, you'll see 0, 1 and then just a blinking cursor :) – Verma Apr 24 '19 at 19:29

4 Answers4

3

continue stops the current iteration of the loop and goes immediately to the next iteration of the loop, skipping over the remainder of the loop body.

In your while loop, the rest of the body includes the statement x += 1. So x never becomes 3, it stays at 2. From then on, the if x == 2: test always succeeds, and it keeps skipping over the increment, and gets stuck repeating that loop over and over.

In a for loop, it skips over the remainder of the loop body, and then gets the next item from the iterator that it's looping over. If you changed your loop to:

for x in range(5):
    if x == 2:
        continue
    print(x)

You would get the output that you were expecting. Incrementing x is not done in the loop body, it's done by the for statement itself. It happens automatically at the beginning of each iteration. So continue only skips over the print statement.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Could you please explain the 'continue' keyword in for loops? I don't think I have understood what it does in for loops. – Röyal Apr 24 '19 at 19:39
  • I added an explanation of how `for` differs from `while`. – Barmar Apr 24 '19 at 19:43
  • Great explanation! I now understand the differences. I needed to realize that the increment is done by ```for``` itself unlike ```while```. Thanks! – Röyal Apr 24 '19 at 19:52
1

The continue keyword in python tells the program to skip over the rest of the contents of the loop and jump to the next iteration.

In your second code, you'll notice that the program never stops executing. That's because once x == 2 is True, the program will go hit continue then jump to the next iteration...where it checks again for x to equal 2 again and will hit continue. This is an infinite loop.

SyntaxVoid
  • 2,501
  • 2
  • 15
  • 23
0

break goes out of the loop right away, continue stops the current iteration to start to next iteration directly (it does not go out of the loop).

Eskapp
  • 3,419
  • 2
  • 22
  • 39
0

The 2nd code example will never terminate, because the continue restarts the while loop without incrementing x.

brunns
  • 2,689
  • 1
  • 13
  • 24