Is_prime: function fails on is_prime(9), returns true when should return false


#1


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

My code for is_prime function is returning the following error: "Your function fails on is_prime(9). It returns True when it should return False."

I expect it iterate through and divide the numbers from 2 to value x - 1 to determine if it is a prime number. I feel like I am so closed but maybe it's how I am iterating n or do I break if statement in my while loop

def is_prime(x):
    if x < 2:
        return False
    elif x == 2:
        return True

    n = 2
    while n < range(2, x-1):
        test = x%n
        if test == 0:
            return False
        else:
            return True
        n += 1

#2

The loop should only return False for rejected values, and continue to completion before returning True.


#3

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

The loop has to iterate through all numbers between 2 and x in order to get to the proper result.
Adding an extra measure to test for each iteration worked for me.


#4

Hi Thanks for your help!

You are using 'test' as iterating variable, so every time x%n =0 there is 1 added to test if x%n !=1 then test doesn't iterate (else statement in the for loop). Then you see if test is greater than 0, then x isn't prime, if test = 0 then x is prime. Are you doing this to catch my rejected values that weren't being caught in my first code?


#5

the problem with your code is that for x=9, the first cases tested by your loop is n=2:

9 % 2 == 0

this condition is false, so else runs, returning True (which will end the function)

but we only want to return True after the loop has finished running

this can also be done using test variable.


#6

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

This code has test variable but is failing at is_prime(4). Why?


#7

because you place test=0 inside the loop, so test will get re-assigned a value of zero each iteration of the loop

so only the last n in range determines if the number is a prime number, which is not a valid way


#8

THANK YOU!! That makes perfect sense!


#9

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