Is_prime


#1



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


Your function fails on is_prime(9). It returns True when it should return False.


Should expect it to return False because 9 % 3 == 0


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


#2

All..

is not necessary. And your indentation here is faulty:

You should return the for loop result. There isn't need for another else.

Please see below for suggested code.

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

#3

bayoishola20, when I remove the elif statements with x == 2 or 3. I receive, function fails on is_prime(2 or 3) respectively. When I run the script you have verbatim, it still fails on is_prime(9).


#4

Please post all code updated.

Thank you! :slight_smile:


#5

I just ran it to check if 2 or 3 are prime numbers and I got True. And for 9, it was False

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

#6

def is_prime(x):
    if x<2:
        print "Not a prime number"
        return False
    elif x==2:
        return True
    elif x==3:
        return True    
    else:    
        for n in range(2,x-1):
            if(x%n==0):
                return False
                break
        else:
            return True
print "Is this number prime?: " + str(is_prime(9))

#7

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