Python Forum

Full Version: Reason of the output
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
The output of this program is
no
but I think it should be yes
because if condition is true when loop iterate last time(3rd time)

I know I am not right, please help me with the reason of "no"

def fun(a,k):
    for x in a:
        if x==k:
            return 'yes'
        else:
            return 'no'
print(fun([6,8,5],5))
run your code on this site
it will help you understand why
http://www.pythontutor.com/visualize.html
It is because you only iterate over the first value, then return when x = 6. If you want it to iterate over all the values, then you need to stay in the loop until a match is found.
def fun(a,k):
    for x in a:
        if x==k:
            return 'yes'
    return 'no'
print(fun([6,8,5],5))