Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Reason of the output
#1
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))
Reply
#2
run your code on this site
it will help you understand why
http://www.pythontutor.com/visualize.html
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
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))
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  coma separator is printed on a new line for some reason tester_V 4 510 Feb-02-2024, 06:06 PM
Last Post: tester_V
  Code used to work, not anymore for no apparent reason? chicagoxjl 1 1,909 Jan-08-2020, 05:05 PM
Last Post: jefsummers
  Syntax error for a reason I don't understand DanielCook 2 2,456 Aug-07-2019, 11:49 AM
Last Post: buran
  "invalid syntax" for no apparent reason wardancer84 2 7,187 Oct-03-2018, 11:57 AM
Last Post: wardancer84
  for some reason this isnt working lokchi2017 3 2,721 Aug-06-2018, 12:24 PM
Last Post: perfringo
  My program subtracts fractions, but for some reason isn't simplifying them RedSkeleton007 9 5,943 Mar-03-2018, 11:45 AM
Last Post: Gribouillis
  What is the reason for this difference between lists and tuples? Athenaeum 3 4,225 Sep-25-2017, 07:16 PM
Last Post: buran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020