Is_prime problem - first return breaks loop, not sure how to overcome?


#1


https://www.codecademy.com/courses/python-intermediate-en-rCQKw/0/6?curriculum_id=4f89dab3d788890003000096

I am stuck with testing whether numbers are prime numbers. When x = 9, I'm assuming it runs through the loop the first time, where 9%2 = 0.5 and therefore returns a "True" and terminates the loop. But I need it to test all the numbers in the list and if any are False, it needs to retrn "False" and I have absolutely no idea how to do this? I'm completely at my wits end and have no idea what I've done that's so stupid. Please Help!!!


def is_prime(x):
    x = int(x)
    if x > 2:
        for n in range(2, x):
            if (x%n) == 0:
                return False
            else:
                return True
    elif x == 2:
        return True
    else:
        return False


#2

it makes sense? functions end the moment a return keyword is reached, which in your case happens in the first run of the loop

You could change the indent of else return True? so you get a for/else, this way else will only run if the for loop finishes running


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.