6 is_prime


#1



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


what is the wrong in this code


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


#2

a function ends the moment a return keyword is reached, this currently happens in the first iteration of your loop.

You only want to return True after the for loop has finished running


#3

Thanks for your reply but i didn't get what to edit in my code


#4

your else/return True so that a return keyword is only reached after the looped has finished running? The loop needs to finish running before returning true, not return True in the first iteration just because the if condition evaluates to false


#5

def is_prime(x):
n = 2
prime = False
if x <2:
prime = False
else:
while n < x:
if x % n == 0:
prime = False
break
else:
n +=1
prime = True
else:
prime = True
return prime

You messed up with some stuff such as your loop. You need a while loop instead of a for one.


#6

All roads lead to Rome, even with a for loop this can be done


#7

4 posts were split to a new topic: 6. is prime


#8

Thanks all for their help....


#9