Is_prime


#1



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


it return error "Oops, try again. Your function fails on is_prime(9). It returns True when it should return False." what's wrong in my code tho ?


Is_prime
#2

You have a loop in your code. How many times should it iterate?

Notice how there are two things that can happen in an iteration of your loop, either False is returned, or True is returned. In both cases, the function and therefore also the loop is exited on the first iteration, there is no scenario where it does a second iteration. How does that compare to what you want it to be doing?


#3

Thanks! that solves my problem :smiley:

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

i simply moves back the else in the if condition


#4

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

should be written as:

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

You're using for-else in a way that makes for-else useless, therefore you should simply remove it.


#5

right , thanks again :grin:


#6

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