0
search =int(input('enter the element to search'))
for x in [1,2,3,4,5]:
    if search==x:
        print('element is found')
        break
else:
    print('element is not found')

why the else statement is not executed here as we know that adding else suite after for loop ,it gets executed anyway

 enter the element to search4
    element is found
  • Does this answer your question? [Opposite of Python for ... else](https://stackoverflow.com/questions/3296044/opposite-of-python-for-else) – wovano May 30 '22 at 10:15
  • The `else` statement for a `for` loop should have been called `nobreak`. – Matthias Jun 24 '22 at 09:10

3 Answers3

4

The else part to the for doesn't get executed anyway. It gets executed only when the loop completes fully and normally without breaking.

search = 4
for x in [1,2,3,5]:
    if search==x:
        print('element is found')
        break
    else:
        print('Element is not found (from if)')
else:
    print('element is not found (from for)')

Output:

Element is not found (from if)
Element is not found (from if)
Element is not found (from if)
Element is not found (from if)
element is not found (from for)
MohitC
  • 4,541
  • 2
  • 34
  • 55
2

... we know that adding else suite after for loop, it gets executed anyway.

You may think that, most seasoned Python developers would not agree :-)

You misunderstand when the else is executed. Specifically, it is not executed when you break from the loop, which you are for the input value of 4.

See here for more detail, in particular, this bit:

A break statement executed in the first suite terminates the loop without executing the else clause’s suite.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
-2

somehow I can feel what u want to do here, to achieve that u need to write as below instead!

search = int(input('enter the element to search\n'))
for x in [1,2,3,4,5]:
    if search==x:
       print('element is found')
       break

if search!=x:
    print('element is not found')
Iraz Irfan
  • 10
  • 5