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


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


#3

Im not sure, but after rechecking the reason:
if x>1 and x!=2: #This basicly says if x>2. As 3 is larger than two it gets in the loop. However, as soon as the loop ends, 3 will still be larger then 2, making the else statement impossible to reach.


#4

3 is not equal to 2 and greater than 1. Shouldn't it go through the for loop? I changed the code to include an else statement.

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 True
                
    elif x==0:
        return False
    elif x==1:
        return False
    else:
        return True 


#5

In this case your else statement is too far indented. It goes into the loop, and then returns False or True effectively breaking the loop.
Once you fix that, you have to figure out a way to deal with negative numbers such as -10. As of yet, they are not in your function.


#6

A minor gripe is that your using range(2,x-1).
Range (2,4) will use the numbers 2, 3.
In this case, the x-1 is automatically applies, as the n will never become 4.
This makes the def skip one division.
range(2,x) shows better understanding


#7

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