Is prime


#1



is prime: what is the problema please?


Oops, try again. Your function fails on is_prime(3). It returns None when it should return True.


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


#2

Try replacing:

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

With:

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

#3

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

Now it says: Oops, try again. Your function fails on is_prime(2). It returns None when it should return True.


#4

I have a feeling you have an indentation error. Can you please post your formatted code? if you need help with formating code in your posts please see:


#5

You are missing condition that 2 is true. Because in the FOR loop the number 2 is not included. if x=2. then range is (2, 1), and then you have empty list.
Therefore just add additional condition elif x==2: return True


#6

The number 2 is included... What do you think elif x >= 2 means?

If you ran my code and called is_prime(2);, it would return true.


#7

Oops! My apologies, it would appear that I'm the one who made the syntax error... Here is what I meant for you to do:

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

Yeah... ... My bad...


#8

I had this problem as well as tons of other people. You need to put the final return statement at the end of the for loop and get rid of the else statement in there.


#9

No you don't... What are you talking about?


#10

It was an indentation error as you said (in the "else" line). Thanks a lot for your help!!!


#11

It worked for me and I saw others do it on the q&a as well.


#12

It may work, but it's inefficient.


#13

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