Help in is prime


#1



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


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


not able to understand why logic fails at 9.Expected it to return False and break at 3.


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


#2

Let x = 9

When i = 2 the if branch fails so reverts to else which returns True. This indicates that there should be no else branch in the if statement.

We really only need a test for less than 2, a for loop to iterate over a range (2, x-1) which may return False, and a final return of True.

    if x < 2: return False
    for i in range(2, x-1):
        # code
    return True

If x == 2 or x == 3 it will not enter the loop and fall directly to the return True. If the loop completes with no return, flow falls to that line, as well.

We never write break after return, btw.


#3

thank you for the reply. Just wish to clarify is range(2,2) a statement which is not executed by python. Is it why x==3 failed?


#4

range(2, 2) returns the empty list, so yes, it will not be executed.

The stop parameter (the second one) is not included in the resulting list. That is why, for example, range(2, 3) returns list [2].


#5

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