Is_Prime


#1



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


This just doesnt want to work!
When I try, it just says that when Is_prime(3), it returns false insted of true, and that happens no matter what I do, Help pls :frowning:


x = input("Input a number to be checked:")
x = int(x)

def is_prime(x):
    n = 1
    if x == 0 or x == 1:
        return False
    elif x == 2:
        return True
    else:
        while n != x:
            if x % n >= 1:
                n += 1
            elif x == n:
                return True
            else:
                return False


#2

important to understand: A function ends the moment a return keyword is reached, if a return keyword is reached in a loop, the loop breaks

So, you only want to return True after the loop has finished running


#3

varley303 I think you get into trouble with your testing.

Everything in the function up to the first else is just testing for the special cases 0, 1 and 2 (if your function doesn't test for them then codeacademy.com's code checker deems this a fail). So the real prime test begins at the while statement.

Your function can only return a result of True if it evaluates elif x == n: as True (or when x = 2) but your while statement only executes as long as x != n so when x=3 and n=3 the while loop stops running and never gets to execute return True


#4

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