pythonscopesfor-else

Python scopes in For -Else


I am learning python and couldn't understand what is going on with flag in the below code snippet. Since I have updated the flag to false with in the if suite, I expect to see false printed from else, but the output shows true. Can someone please help me understand what is going on here.

objects=[1,2,3,4,5]
found_obj = None
for obj in objects:
    flag = True
    if obj == 3:
        found_obj = obj
        print("found the required object ",found_obj)
        flag= False

else:
    print ('Status flag ::', flag)

The below is the output I get when executing this code

found the required object  3
Status flag :: True

Solution

  • You set flag = True in the beginning of every iteration, thus it prints true where it is assigned to true in the last iteration where obj equals to 5

    You might want to correct it by moving out flag = True from the for-loop:

    flag = True
    for obj in objects:
        if obj == 3:
            found_obj = obj
            print("found the required object ",found_obj)
            flag= False
            break  # no need to continue search