6 is_prime wrong code


#1

Hi everyone!

I can't figure out why my code doesn't work, the editor says: Your function fails on is_prime(2). It returns Non when it should return True.
My code:

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
x = int(raw_input("Insert number: "))
print is_prime(x)

#2

to help with your current error, your function will indeed fail on 2.

x < 2, which is false. 2 isn't smaller then 2

for n in range(2,2-1):
hm.. the loop won't run. the steps are +1, and 2 isn't lesser then 2-1. So indeed 0 is returned. maybe make elif for 2?


#3

Thank you very much for helping me to improve, I'll try to fix my code. :slight_smile:

P.S. I'm sorry for posted unformatted code, this is my first post, I have to understand better how forum works.


#4

if you need more help, post an updated version of your code


#5

The code works now, thank you very much again. :slight_smile: