Is_prime


#1

Keep on getting error: Your function fails on is_prime(0). It returns None when it should return False.
This is my code:
def is_prime(x):
for x in range(2, x-1):
if x%2== 0:
return False
else:
return True


#2

x is already defined as the input parameter, so we should not be assigning a new value to it. Try a different variable, such as n...

for n in range(2, x):

It is not parity that we are checking (divisible by 2) but divisibility by any number, n.

    if x % n == 0:

#3

Okay, thanks. I made those changes, but now I get an error that says Your function fails on is_prime(0). It returns True when it should return False.
My code is:

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

#4

You're very close, now. Consider that, a) prime numbers are not negative, and, b) zero and 1 are not prime. So that means we can elliminate any number less than two, right off the top.

if x < 2: return False

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

	
>>> is_prime(9)
False
>>> is_prime(2)
True
>>> is_prime(0)
False
>>> is_prime(3)
True
>>> is_prime(4)
False
>>>

#5

Thanks! That fixed it.


#6

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