Is_prime function returning True on 0


#1



https://www.codecademy.com/courses/python-intermediate-en-rCQKw/0/6?curriculum_id=4f89dab3d788890003000096


I'm getting "Oops, try again. Your function fails on is_prime(0). It returns True when it should return False."


I must have my math wrong somewhere but It should (obviously) be returning false. but It's returning true. I've even gone so far as to add a specific if statement to the function to return False if 0 is entered as x and it still spits out True. Side note, it's not printing what I say when I say print " Not a Prime" or "It's a Prime".


def is_prime(x):
    for n in range(2 , x - 1):
        if x == 0:
            return False
        elif x%n == 0:
            return False
            print "Not a prime!"
    else:
        return True
        print "It's a Prime!"
print is_prime(0)


#2

i think you don't fully understand that your for loop won't run.

for x=0, the for loop would be the following:

range(2, -1)

2 is greater then -1, so the for loop never runs


#3

I fixed it by jerry rigging the code into doing what I wanted it to lol

def is_prime(x):
    if x >= 2:    
        for n in range(2 , x - 1):
            if x%n == 0:
                return False
                print "Not a prime!"
        else:
            return True
            print "It's a Prime!"
    else:
        return False
print is_prime(20)

but it still is not printing the things I'm telling it to print, any ideas on that?


#4

a function ends the moment a return keyword is reached, so the print statement after return are never reached. I would swap return and print line around if you want the print lines to be reached


#5

Thanks! That did it.


#6