How to solve for negative numbers in is_prime()


#1



is_prime


The error that I get is :
Oops, try again. Your function fails on is_prime(-7). It returns True when it should return False.


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


#2

I would use the abs() function to make sure the input is processed as a positive number.


#3

Doing that would result in negative prime numbers, the assignment specifies everything below 2 as a nonprime.


#4

My bad, it's been a while since I read those instructions.


#5

Your not doing anything with the numbers below 0.
You should modify the if x == 0 or x == 1: to include these numbers. They are all less then 2.


#6

Thank you very much. It worked :slight_smile:


#7

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