# Stuck in is_prime

#1

def is_prime(x):
if x>1:
for i in range(2,x):
if(x%i)==0:
print "x,is not a prime number"
break
else:
return True
print "x is a prime number"
elif x==0:
return False
print “False”

else:
return False
print “x,is not a prime number.”

print is_prime(4)

INSTRUCTIONS:
Define a function called is_prime that takes a number x as input.

For each number n from 2 to x - 1, test if x is evenly divisible by n.

If it is, return False.

If none of them are, then return True.

ERROR TYPE:
Your function fails on is_prime(2). It returns None when it should return True.

#2

Statement after return is not reachable. Your function should only detect primes and not print anything. Just return True or False.

#3

def is_prime(x):
if x>1:
for i in range(2,x):
if(x%i)==0:
return False
break
else:

``````      return True
``````

elif x==0:
return False

elif x==2:
return True

else:
return False

print is_prime(4)

ERROR TYPE:

Your function fails on is_prime(2). It returns None when it should return True.

#4

`break` is unreachable after `return`. Just remove it.

The if statement should not have an `else` branch. The loop must finish iteration.

``````if x > 2:
``````

Remove all those lines. Just have the function return True after the loop. Be sure it is not inside the loop or the if.

#5

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

DOESN`T WORKS!

#6

Close, very close. Remove the `else:` and return True on the last line.

``````if ...
for ...
if ...
return False
return True
``````

For the opening line of your function, try,

``````if x < 2: return False
``````

then start your for loop on the next line.

#7

Hi,
I don’t understand why the code fails for 0

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

#8

Because in order for your function to operate correctly it must filter the obvious non-primes at the start.

``if x < 2: return False``

#9

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