-1

I was working on a project and have replicated my doubt by a simple example. I am unable to understand the control structure of the following python code snippet.

list1 = [1,2,3,4,5]
for item in list1:
    if item == 3:
        print("Found")
        # break
else:
    print("Not found")

Note: Please note that the indentation of the else part is intentionally kept so and I thought it would through an error but it gives the following output:

Found
Not found

Also if we uncomment '# break' the output is:

Found

Why isn't this code throwing an error.If it's working as per if else conditions then the expected output should be:

Not Found
Not Found
Found
Not Found
Not Found
Omkar
  • 791
  • 1
  • 9
  • 26
  • 3
    Python `for` loops can have an `else` clause. See the [manual](https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops) – Nick Jun 26 '20 at 06:46

2 Answers2

1

The else condition in the code is for the for loop and not from the if statement since that you are getting Not found in the end because it's getting executed after the last for loop iteration.
In this code the indentation of the else is for the if

list1 = [1,2,3,4,5]
for item in list1:
    if item == 3:
        print("Found")
        # break
    else:
        print("Not found")

and that outputs

Not found
Not found
Found
Not found
Not found
Leo Arad
  • 4,452
  • 2
  • 6
  • 17
0

to understand it more clearly place another else loop for if block... current else block is for for loop

Sandeep Kothari
  • 405
  • 3
  • 6