6. is_prime What's wrong with my code? Please help


#1




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


I can't get what's wrong with my code. Please help!


x = raw_input("Please enter the prime number:  ")

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


#2

in the first run of the loop, a return keyword is reached (either return True or return False), but you only want to return True after the loop has finished running

Try changing the indent of else/return True so that True is only returned after the loop has finished running

important: a function stops the moment a return keyword is reached, so currently your loop only makes one iteration


#3

Thank you! It helped

Now I want to print out the conclusion, but it isn't printed:

x = raw_input("Please enter the prime number: ")

def is_prime(x):
if x < 2 :
return False

for n in range(2, x - 1):
    if x % n == 0 :
        return False
        print "This is not a prime number"
else:
    return True
    print "This is a prime number"

Can you guess what do I do wrong this time?
Thank you!


#4

so it never gets to the print line. you could simply print what is returned by adding a function call:

print is_prime(x)

#5

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