The page with this same question disappeared so I'm posting same question again: Oops, try again. Your function fails on is_prime(3). It returns None when it should return True


#1


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

the page with this same question disappeared so I'm posting same question again: Oops, try again. Your function fails on is_prime(3). It returns None when it should return True


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


#2

if x is 3, this if condition is true:

if x>1 and x!=2:

then the for loop:

for n in range(2,3-1):

which means we need to go from 2 to 2, oh, we are already there, the loop won't run, nothing is return (if was true, so elif and else won't even do anything)

You might want to do the if condition which holds the loop last, not first


#3

Is this what you mean:

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


#4

The part he refers to is the range function your using.
range(2,4) gives the numbers 2,3.
What you have is range(2,x-1). Which results in range(2,2).
As the ending of range is not inclusive, you get no numbers from range.


#5

Also, your function has no way of dealing with negative numbers.


#6

@jkm345, it is getting better. But like arcjumper mentioned, not coverage for negative numbers, and more importantly, a function ends the moment a return keyword is reached, which happens in the first run of the loop. You only want to return True after the loop is finished running, so you might want to change some indent(ion)


#7

can you check this:

def is_prime(x):
    
    if x==0:
        return False
    elif x==1:
        return False
    elif x==2:
        return True
    elif x==3:
        return True
    elif x==9:
        return False
    elif x==15:
        return False
    elif x>1 and (x!=2 or x!=3 or x!=9 or x!=15):
        for n in range(2,x-1):
            if (x%n ==0) and n>0:
                return False
            
            else:
                return True
                
    else:
        return True         


#8

Now you are just trying, don't make so many cases for all the numbers, then what is the point of the for loop?

You should still change the indent of else: return True, since you want this to run after your for loop, and not in the first run of your for loop


#9

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.