6. is_prime


#1



Why doesn't the following code work?


I get the error: Your function fails on is_prime(2). It returns None when it should return True.
Thanks in advance


def is_prime(x):
    if x < 2:
        return False

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


#2

First of all, after your first if statement, you should have an elif next, then an else but that's not what you have.

To get it to return as in to print True, you might need to use print while calling that function, like below:

print is_prime(2)

That way, it will print True as it were and the default None after that.

Hope this helps! :slight_smile:


#3

I am confused at how this is meant to help me. I can't seem to get my code to work and it is the same as the code above. I don't understand how I am meant to fix this.


#4

You should post your new code after implementing my suggestion so that I could help. :slight_smile:


#5

Well, this is what I suggested in summary:

def is_prime(x):
    if x < 2:
        return False

    else:    #I removed if or elif as it were
        for n in range(2, x):
            if x % n == 0:
                return False
        return True
print is_prime(6) # to see what I have done, I used the print method on the calling the function.

#6

Oops, try again. Does your is_prime function take exactly one argument (an integer)? Your code threw a "unsupported operand type(s) for %: 'int' and 'tuple'" error.

I keep on getting this error. I tried a different code. My code looks like this now:
def is_prime(x):
n = 2, x - 1
if x % n:
return False
else:
return True

Please help.


#7

NVM. This worked fine. I just don't understand how it works. I am surprised that I can get this far, everyone else in my year 10 computing class continuously calls me an idiot.


#8

You're welcome.

Yes, those code, I suggested works fine. I tested it.

Please see my suggestion in first reply to better understand this!


#9

sorry. I was busy trying to work on it when you posted a solution.


#10

Hi
i used a 'break' in the conditional 'if'
hope my piece of code can help you

def is_prime(x):
if x<2:
return False
elif x==2: # I put this conditional because I have trouble with the integer 2 (i dont know why)
return True
else:
for n in range(2,x):
if x%n == 0:
return False
break # here is the break
else:
return True

for ii in range(20): # this is for checkin the first 20 numbers
print ii, is_prime(ii)


#11

Thanks very much, it works now


#12

You're welcome @tharindu.w.

Have fun coding! :slight_smile:


#13

Thank you. I found this very helpful.


#14

what do you do about the case where x = 2? why does it cause trouble and is there a more elegant solution than "elif x==2: return True"?


#15

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