Python Forum
Reason of the output - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Reason of the output (/thread-26320.html)



Reason of the output - himanshub7 - Apr-28-2020

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))



RE: Reason of the output - buran - Apr-28-2020

run your code on this site
it will help you understand why
http://www.pythontutor.com/visualize.html


RE: Reason of the output - TomToad - Apr-28-2020

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))