Is_prime help!


#1

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

is_prime(x)

Why isn't my code working? I'm finding it difficult to solve it.


#2

a function ends the moment a return keyword is reached, so your loop ends in the first iteration of your loop, this can't be right, True should only be returned after the loop has finished running. and your if x % i == 0: is wrongly indented, it should be in the for loop

the function call should have an actual number as argument


#3

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

This is what I've done now. And this is the message I get.
Oops, try again. Your function fails on is prime(9). It returns True when it should return False.


#4

a function ends the moment a return keyword is reached, so your function ends in the first run of the loop, but we only want to return True after the loop has finished running (this is the condition for a number to be a prime number)


#5

Hi,
In this program the following aspects need to be considered-
1. Make sure the number is positive
2. 0 and 1 are not prime
3. 2 is prime
4.Then monitor the for loop for any other input, so, at least one case where the number is divisible is detected, which should result in break from the loop


#6

I get it! thanks guys!


#7