Is_prime help please


#1

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

but why? I don't understand.

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

#2

elif is true for x=2, so else return True will never run

Simply remove else so return True is returned when the loop finishes


#3

ok so I removed the else, and changed return to return True when loop finishes, but I am still receiving the same error.

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

#4

the placing of the return True was fine. Please think about changes you are making, a number which has a remainder of zero is never a prime number


#5

thanks again for the assistance. this is becoming increasingly difficult. glad to have people like you out there to help.

this ended up working for me. I just wish it didn't take over hour to figure it our LOL

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

#6

can someone let me understand why the last else is used with the for loop and not with the if x%n==0?
i think if and else should be a part of for loop instead


#7

no, it shouldn't. Because then, in the first iteration either if is true, or else will run, either way, a return keyword is reached in the first iteration, causing the function to end (this will break the loop)


#8

got it.thanks
but does that mean that i never need an else dialog with an if statement
"""
if x>10:
return True
return False
"""
should be valid as well as an alternative to
else:
return false
??


#9

given you use return here, there isn't much difference but if you had:

if x > 10:
    print "greater then 10"
else:
   print "not greater then 10"

or:

if x > 10:
    print "greater then 10"
print "i am always printed"

here it matters


#10

oh okay. i got it now.thanks


#11

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