Need help w/ is_prime (Practice makes perfect 6)


#1



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


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
    else:
        return False


#2

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

Thank you!


#3

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
else:
return True


#4

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.


#5

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


#6

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

:slight_smile:


#7

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
    else:
        for n in range(2,(x-1)):
            if x%n == 0:
                return False
        return True
print is_prime(9)

#8

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


#9

Okay, you're welcome.

Do you mind sharing it? :wink:

Have fun coding! :slight_smile:


#10

Of course!


#11

Cool!

Awesome! :slight_smile:


#12

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


#13

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