Avatar of nachtmsk
Flag for United States of America

asked on 

For Loop in Python - Logic Question

My 11 year old son is going through a Python book and he came across nested loops.
He has the program below and asked me how to stop the "No" response from showing up for each instance of a non-match.
We are both trying to modify the code to only have "no" print out once if a number isn't found as opposed to having it print out each time.

I don't see how it can be done within the loop. I have an idea to dump all of the "yes" numbers into a list, then dump all of the "no" numbers into another list. Then print out each list out of the nested for loop.
That will probably work, but we are both trying to find the right logic to use within the nested loop to do the same thing.

Hope I made myself clear. Thanks for your opinions.


## The problem:
        # We have two lists of numbers. What numbers in the first list are in the second list?
for x in [1,2,3,4,5,6,7,8,9]:
        print "Checking number: " + str(x) +  " to see if is in second list"
        for y in [2,23,6,78,9]:
                if x == y: # If the first number (x) is equal to the second number (y)
                        print "yes! " + str(x) + " is in both lists"
                        print "No",x

Avatar of undefined
Last Comment

8/22/2022 - Mon