is_prime issue


#1

Hello, thisreturns all types of errors when I am trying to submit it on codecademy. I am sure it's something that I'm missing, Can you see what it is and why it is not working on codecademy,

Thank you all very much.

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

#2

Hello @corewhiz33926_541a18

In you code, at the end, you have


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

replace that with

'else:
    for i in range(2, int(x ** 0.5) + 1):
        if x % i == 0:
            return False
        
return True'

It should work.


#3

@corewhiz33926_541a18 what's wrong in your code?
I wrote the same. If you have found your mistake will you please tell me what is it


#4

Seems like you dont understand what range is actually doing.
range(2,5) is (2, 3, 4) so you dont need that x -1 just simply put range(2, x)
and you need another if statement for x == 2, because range(2, 2) is 0.
so your code should be something like this:

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

#5

The exercise says "For each number n from 2 to x - 1, test if x is evenly divisible by n." I did it like this, which doesn't need the 'if x == 2' condition:

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

#6

def is_prime(x):
    if x < 2:
        return False
    else:
        for i in range(2, int(x ** 0.5) + 1):
            if x % i == 0:
                return False
    return True

This worked for me