I can not get is_Prime working


#1



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


I keep getting an error message with is_prime(4) returns True when it should return False


is_prime(4) should be False sense 2 % 4 = 0


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


#2

your for loop only runs once, because in the first run of the loop a return keyword is reached (if is true, or else runs), either way a return keyword is reached, causing the function to end. You might want to change the indent of else/return True, so that True is only is returned after the loop is finished running.

uhm.. this line:

if n % x == 0:

i would swap n and x, i would check if the remainder of all the numbers between the number entered (x) and all lower values (n, thanks to the loop) has a remainder is 0, which indicate the number isn't a prime


#3

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