Is_prime

#1

Oops, try again. Your function fails on is_prime(4). It returns True when it should return False.

I don't understand how this return True when my loop for x = 4. It should process 4 % 2 == 0 thus returning False...please help!

``````def is_prime(x):
if x < 2:
print (x, ' is not a prime number!')
prime = False
elif x == 2 or 3:
print (x, ' ia a prime number!')
prime = True
else:
for n in range(2, (x - 1)):
if x % n == 0:
print(x, ' is not a prime number!')
prime = False
break
else:
print (x, ' is a prime nubmer!')
prime = True
return prime``````

#2

this condition isn't right:

``elif x == 2 or 3:``

you need to apply comparison at both sides of the `or` operator, otherwise python will just evaluate if `3` is true, not if x equals 3

note: 3 is considered true:

``````if 3:
print True``````

so your elif condition is always true at the moment, no matter what `x` is

#3

Thanks! Its always something so small I miss while learning this.

#4

Did you figure it out? Its not the only problem in the code, but i wanted to give you a change to find that yourself, but if you need more help, let me know (include an updated version of your code)

#5

My updated code is below. All I did was make that small change and it worked. If there are other issues (other than a couple typos in the print strings which I fixed) I don't see them...

def is_prime(x):
if x < 2:
print (x, ' is not a prime number!')
prime = False
elif x == 2 or x == 3:
print (x, ' is a prime number!')
prime = True
else:
for n in range(2, (x - 1)):
if x % n == 0:
print(x, ' is not a prime number!')
prime = False
break
else:
print (x, ' is a prime number!')
prime = True
return prime

#6

I see what you mean now. In my else block I am testing the number 2 through both conditions. So essentially I am testing if a number is odd or even...

#7

So, all sorted now or are there still problems?

#8

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