-2

The output of the print function differs based on its placement in the code, that much is clear to me.
However I can not conclude why it does that.

1.

fruits = ["apple", "banana", "cherry"]
for x in fruits:
  if x == "banana":
    continue
  print(x)

2.

fruits = ["apple", "banana", "cherry"]
for x in fruits:
  if x == "banana":
    continue
    print(x)

3.

fruits = ["apple", "banana", "cherry"]
for x in fruits:
  if x == "banana":
    continue
print(x)

Number 1 will output apple and cherry while Number 2 will print nothing and Number 3 will print only cherry.

I do understand that continue will skip the loop for banana and therefore not print it, yet I"m not sure why 2. print nothing and 3. prints cherry.

Blaztix
  • 1,223
  • 1
  • 19
  • 28

4 Answers4

1

In 3, the print(x) is not part of the loop. So it prints whatever the last value of x was(cherry).

In 2, the print(x) is never executed since it's just after a continue - which makes the control go to the top of the loop.

rdas
  • 20,604
  • 6
  • 33
  • 46
0

The print() in number 2 is unreachable, as it is behind the continue and will never be executed.

Christoph Burschka
  • 4,467
  • 3
  • 16
  • 31
0

In 1. Every fruit is printed except banana. Because as x equals banana, the if statement becomes true, and that iteration is skipped,the control doesn't move to print statement. Here the print is outside if but inside a for loop. This prints each value unless a continue statement is there. In 2. The print is inside if statement. So only if x==banana then it tries to print but before that is continue! So the rest code is skipped before print statement. In 3. The print is outside the for-loop. So after the for loop finishes the value of X which is cherry is printed.(as it is last value in list)

Tojra
  • 673
  • 5
  • 20
0

In the first case the print statement is inside the "for" loop but outside the "if" statement (which does nothing) so the output is:

"apple"
"banana"
"cherry"

In the second case the print is inside the "IF" but it is following the "continue" statement (instruction that exits the execution of the script from the "if".) : it will never be executed.

If you want the variable to be printed in case 2 contains "banana" you must delete the continue statement, or write it after the print statement

In the third case the print statement is outside the "FOR" cycle and prints the contents of the last assignment to the "X" variable - in this case "cherry".

num3ri
  • 822
  • 16
  • 20