vendredi 26 juin 2020

Tricky python control flow [duplicate]

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

Aucun commentaire:

Enregistrer un commentaire