Is_prime


#1

Can you help me understand this? :slight_smile:

def is_prime(x):
if x==2:
    return True
else:
    if x>2:
        for n in range(2,x-1):
            if x/2==int():
                return False
            else:
                return True
    else:
        return False

It says: "Oops, try again. Your function fails on is_prime(3). It returns None when it should return True."


#2

There's a couple problems, first is your indentation, your if statement should be indented and all other statements should be even with it.

Second, your else statements should be elif statements.

And third, you should compare with "x == 2", not "x==2".


#3

Try this.

def is_prime(x):
if x==2:
return True
elif:
if x>2:
for n in range(2,x-1):
if x/2==int():
return False
elif:
return True
else:
return False


#4

But indent it correctly,


#5
def is_prime(x):
if x == 2:
    return True
elif x > 2:   
    for n in range(2,x-1):
        if x/2 == int():
            return False
        elif x/2 != int():
            return True
        else:
            return False

Tested that... Says: "Oops, try again. Your function fails on is_prime(0). It returns None when it should return False."


#6

Try this, and if not then i'll show you the code I put.


#7

That throws syntax on me... I am curious to know why my code is not working...


#8

your code is not correct, because in first loop return some thing(may be else) and so on your function stoped.

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

this is correct. your error say can't understand 0 is prime or not.
in this code for numbers below of 2 (x < 2) return false that say is not prime. if is 2 or upper, go to a loop from 2 to x for check the x is divisible to that number, if yes return false that means is not prime.
if not accured that, means not divisible, now can return True


#9

Can you please explain how this code works when x = 2?.

Specifically if x = 2, you get range(2,2) which should generate an empty list right? So what exactly happens in the for loop if you're calling on an n in an empty list?


#10

you get range(2,2) which should generate an empty list

yes it's right but see this.
2 is prime
when x=2
if x<2: --- False
else: ---run now
for n in range(2,2): --- n in empty list, then this loop have no run, and so on go after the loop and return True

that means 2 is prime :smiley:

other says: your code can be wrote in many models, and each of them can be work correctly, that have single different by other code, that different is on run time.

excuse me,my english language is not good :wink:


#11

Thank you! I've been having the same problem but I never thought I could just write return True under the else without writing another else under the else (does this sentence even make any sense lol)


#12

I understand. Thank you very much! Your English is fine :smiley: