#6 - Is Prime - not elegant, but cannot decipher why it does not work


#1

Hello all,

I realised after that the start part of this code is ugly, but in this case I cannot work out why the below does not work. I get None.

Help appreciated!

def is_prime(x):
    if x == 0 or x == 1:
        return False
    elif x == 2:
        return True
    else:
        for i in range(2,int(x-1)):
            if x % i == 0:
                return False
            else:
                return True

#2

Ignore me! I spotted my glaring error.

 for i in range(2,int(x-1)):

should be

 for i in range(1,int(x-1)):

However, I am still getting is_prime(3) returning False...
:expressionless:


#3

What should it have been doing to determine that 3 is prime?
Not a whole lot of things, but which? Have a look at whether it did those things.


#4

I had same code / problem. This helped me:

From: bibleman13

I believe this will help you out! All credit to Factoradic as well I didn't come up with this answer.

Is_prime for some reason doesn't work on number 9
Ok, so let us assume that x = 9, what happens in your code?

It starts with the if, but 9 < 2 is False so we go to the elif. 9 == 2 is False so we go to the else.

Now we have a for loop and the first value of i is 2.

The condition of if is 9 % 2 == 0, this is obviously False, but there is an else block, so we go there. And there is only a single statement - return True and this value will be returned.

In other words, your code will return True for every odd number that is > 2.

To solve this problem you can move return True outside the for loop.

Also from bibleman13

Also this from Stetim94 might help as well. Once again all credit to Stetim94 I didn't come up with this answer.

Is_prime: problem with "Your function fails on is_prime(9)"
a function ends the moment a return keyword is reached, in your case this happens in the first run of the loop.

You want to change the indent of else/return True, since you only want to return True after the loop has finished running


#7

def is_prime(x):
    n = abs(x)
    if x<2:
        return False
    elif x==2:
        return True
    elif x>2:
        if n%2 == 0: 
            return False
        else:
            return True
            
print is_prime(9)

I am also stuck with 9.
I tried to put return outside the function, like sugested, but it doesn't work.
Have i made any other mistakes?


#8

your last else: should be on your for loop not your if statement. Your ending the for your for loop on your first iteration otherwise :wink:


#9

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