Problem 6: is_prime


#1



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

This is my code for the problem. I am having problems understanding why it gives False instead of true when the input is . Could someone please explain where I have an error in my logic


#2

it's your range limits.

for n in range(2,x):

by allowing the top of your range to continue to x, the function is able to divide x by itself resulting in no remainder.

Try changing the range function to:

for n in range(2, x-1):

Let me know if that helps at all!


#3

From my understanding, when using range, the first value is inclusive, and then the second is exclusive.
Anyways, I was able to solve the challenge by taking out the else that was nested inside the for loop, and moved it back so it was paired with the for loop.


#4

You have the correct understanding of range(). It returns a list that does not include x. Good that you were able to discover the error in your code (the else statement).

  elif x == 1 or x == 0 or x < 0:
      return False

There is enough information and testing without the need of the last test. That line could just be,

return False

#5

I didn't know the last value was exclusive. Though that does explain why some of my earlier functions didn't pan out!


#6

I think the problem is in your else statement. check the indentation. i think the else should belong to the for, not to the if. if you use it the way you did, the first n of your range that is no divisor of x will cause the else to return True.


#7

Of the above, this is all you need:

    elif x > 2:
        for ...
            if x % n == 0:
                return False
        return True

    return False