Is prime is giving me errors


#1

So my code is

def is_prime(x):
if x == 1 or x == 0:
    return False
else:
    for n in range(x):
        if x%n == 0:
            return False
        else:
            return True

but I don't know what is wrong with it. The error message is
"integer division or modulo by zero"
If you know what is wrong help would be appreciated.


#2

The first n in the for-loop is 0, so you try to divide x with 0, which gives the error.


#3

i tried this with range(2, x)
still didn't work. I even tried with range(2, x-1) nada.
Any suggestions?


#4
if x%n == 0:
    return False
else:
    return True

You return True as soon as you find an n with x % n != 0. But you need to make sure that's true for any n > 1.

You should only return True after the loop finished.


#5

You get that error message because of your else part .Consider x =3, then it would directly go to the Else part and in the for loop n would assume 0 as the first value in the range -> that leads to the float by zero error


#6

You should check if x < 2 first and it should return false after that in an else statement loop through it with you range being 2,x and check if x%n == 0 and then return false if it does. You should return true otherwise but your return true statement should be out side the for loop. Hope this helps