+ 1

Why this continue statement is not working?

Pease explain why continue statement is not working in this code . Why I am getting output as "Cherry" Only fruits = ["apple", "banana", "cherry"] for x in fruits: if x == "banana": continue print(x)

25th Apr 2021, 4:34 AM
Aman Kumar
Aman Kumar - avatar
6 Answers
+ 2
Aman Kumar # Your Code fruits = ["apple", "banana", "cherry"] for x in fruits: # In first iteration it's apple then banana and at last it's cherry if x == "banana": continue # Because of no indentation the compiler takes this print statement out of the loop and as the last item was cherry the value of x will the last element i.e. cherry print(x) For correct code se AJ's answer.
25th Apr 2021, 5:59 AM
Krish
Krish - avatar
+ 3
Thanks for the information
25th Apr 2021, 7:04 AM
Aman Kumar
Aman Kumar - avatar
+ 2
Aman Kumar Indentation problem. You have to use print statement just below if statement like this fruits = ["apple", "banana", "cherry"] for x in fruits: if x == "banana": continue print(x)
25th Apr 2021, 5:30 AM
A͢J
A͢J - avatar
+ 2
Aman Kumar As there is no opening and closing curly brackets in Python, indentation is more important. As you were printing value of x outside the loop so whichever last value comes that will be print. That's why the output was "Cherry"
25th Apr 2021, 6:21 AM
A͢J
A͢J - avatar
+ 1
Why it is printing only "cherry".Why not other items
25th Apr 2021, 5:25 AM
Aman Kumar
Aman Kumar - avatar
0
The code works. It doesn't show any error. But why it is printing "Cherry" Only. That's my doubt
25th Apr 2021, 5:36 AM
Aman Kumar
Aman Kumar - avatar