Is_prime


#1



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

Hi!
I get an error message "Oops, try again. Your function fails on is_prime(9). It returns True when it should return False.", however i do not know why.
My attempt looks like:


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

I checked my code outside of codeacademy with

def is_prime(x):
    if x < 2:
        return False
    elif x == 2:
        return True
    elif x == 3:
        return True

    for n in range(2, x-1):
        if x % n == 0:
            print n,False
        else:
            print n,True


is_prime(9)

That prints:

C:/Users/********/PycharmProjects/untitled/asd
2 True
3 False
4 True
5 True
6 True
7 True

Process finished with exit code 0

I clearly see a False there at 3 that should return False in the original version. Why am I wrong?


#2

codecademy wants you to return if the number is a prime, the problem is that once a return keyword is reached, a function ends (even while in the process of the loop)

In your case, a return keyword is reached in the first run of the loop. you should change the indent of return True so that true is only returned after the loop has finished running.


#3

I think I see. It surprises me though, beacuse the task was to define a function that decides wether the input is prime or not. At this point my code seems to be OK.I wasn't told the function has to handle many events (however as I guess it runs from 0 to 9 (at least) and there are several primes and not primes that passed succesfully before reaching 9)


#4

but the instruction clearly states:
If it is, return False. If none of them are, then return True.

this clearly indicates you should use return.

Of course you function is tested for some numbers, otherwise it wouldn't be very useful


#5

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