-5

My question is about break statement in python

in this code, x is a iterator. for first iteration apple will store in x and and then print in the second iteration banana will store in x but because of break it will not print.

my question is why it will not print even after it is stored in x. what happen after break statement. where's that banana goes.

fruits = ["apple", "banana", "cherry"]
for x in fruits:
  if x == "banana":
    break
  print(x) 
hiro protagonist
  • 44,693
  • 14
  • 86
  • 111
  • `print(x)` is not in the scope of the if-block. – DirtyBit Apr 03 '19 at 07:23
  • you just don't reach the `print` statement after `break`... if you still wanted to see `'banana'` printed you could move the `print` statement up so that it is right below the `for` line. – hiro protagonist Apr 03 '19 at 07:23
  • 1
    This question lacks minimal understanding of basic control structures. I suggest [reading the docs](https://docs.python.org/3/tutorial/controlflow.html#more-control-flow-tools), there's also [Wikipedia](https://en.wikipedia.org/wiki/Control_flow#Early_exit_from_loops). Bananas can wait, this comes first. – cs95 Apr 03 '19 at 07:25
  • you are not storing anything here you are just comparing it – rahul.m Apr 03 '19 at 11:41

1 Answers1

2

OP: my question is why it will not print even after it is stored in x.

Nothing is being stored here but compared

Debugging:

fruits = ["apple", "banana", "cherry"]
for x in fruits:          # for each fruit in fruits
  if x == "banana":       # the cond is False for the first iter  
    break
  print(x)                # prints apple

For the second iteration, the condition is True and it breaks outta the loop. Hence the only output you get is apple

The correct snippet being:

fruits = ["apple", "banana", "cherry"]
for x in fruits:         # for each fruit in fruits
  if x == "banana":      # if the fruit is banana
    print(x)             # print the banana
    break                # break from the loop
DirtyBit
  • 16,613
  • 4
  • 34
  • 55
  • I don't want to print banana, i just wanted to know if x is already holding banana then where it goes. it should print banana and skip cherry. – vishakha mote Apr 03 '19 at 07:46