Need help w/ is_prime (Practice makes perfect 6)


I initially had my range at (2, x-1) but after reading another question I realized it was not inclusive so I changed it to (2,x). After that, my code worked for is_prime(3) (it hadn't been until then). But now, it still doesn't work for is_prime (9), and returns the error message "Oops, try again. Your function fails on is_prime(9). It returns True when it should return False."

It should return False, I know that, but I don't understand why the code isn't running the number correctly. Help would be appreciated.

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


Please could you post the code you wrote for that instance so I could see why it wasn't all inclusive.

Thank you!


You cannot have two "elif" statements in the same loop. You should delete the next elif (delete this)
elif x%n!=0:
return True
so that you have:
for n in range(2,x):
if x % n==0:
return False
return True


I updated the code but I still get the same error message. Also, I know the "for n in range" bit is repeated- I fixed that but it still won't work.


It was the exact same code as above, just the range was (2, x-1) instead of (2, x)


Erhmm... I didn't write any line of code. I guess you were referring to @solmurphy05 ?



Erhmm... Let's simplify things a little bit.

Back to using what you said you tried and it didn't work.

How about we test if the parameter called is less than 2; then, we loop for a range starting at 2 to one less that the parameter being called.

See sum below.

def is_prime(x):
    if x< 2:
        return False
        for n in range(2,(x-1)):
            if x%n == 0:
                return False
        return True
print is_prime(9)


Thank you so much for your help- I figured it out.


Okay, you're welcome.

Do you mind sharing it? :wink:

Have fun coding! :slight_smile:


Of course!



Awesome! :slight_smile:


I ma glad you found help.I am just logging in now


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