Oops, try again. Your function fails on is_prime(2). It returns None when it should return True


#1



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


Oops, try again. Your function fails on is_prime(2). It returns None when it should return True.


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


#2

The above line allows 2 into the loop, so returns False. The elif case is never reached.

We can see other issues with the logic, as well. Pencil through the code with 2 in mind. Consider also the condition:

if (x % n > 0)

This is an open-ended condition that will be True many times in the course of iterating over the range resulting in false positives.


#3

I get error message: Oops, try again.
Your function fails on is_prime(3). It returns None when it should return True.

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

can you check my code:

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


#4

Remove the above from the if statement. There is no else case. Try this fix, then repost and we can discuss any remaining issues.


#5

I get this error message: Oops, try again.
Your function fails on is_prime(3). It returns None when it should return True.

here's my code:

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


#6

The else: return False is still there. Please remove it and try again.

And, restore this code,

    else:
        return True

#7

ok but i get the same message


#8

here's my code

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
        

#9

What happens when x is 3?


#11

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