Is_prime


#1

"Oops, try again. Your function fails on is_prime(0). It returns None when it should return False."
I don't understand why this doesn't work. In my code it tests for a number below 2, and if it is below 2 it returns false, yet this error message still pops up.

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

#2

Problem1.

  if x < 2:
            return False

This line does not work when number is less than 2.
as range will be an empty list.
(separately check this condition at starting of functions body)

Problem2.

elif x % n != 0:
            return True

No need to add this line,
Just return True at end of function.
Indent it as same level as for loop.

Reason:

elif x % n == 0:
            return False

This line checks all conditions,when It does not run means a number is a Prime,so just returning True will be suffice.
(one more thing to note when you fix the problem 1 and put that code outside of loop body,Then don't forget to change elif toif )


#3

Thanks! That fixed it.


#4

good work! cheers! :thumbsup:


#5

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