Why are my conditions to test for a prime number wrong


#1



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


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


it should work because, as far as I can tell my conditions are correct.


def is_prime(x):
    x=str(x)
    if x=="1" or x=="0":
        return False
    elif x=="2"or x=="3":
        return True
    for num in range(2,(int(x)-1)):
        x=int(x)
        num=num
        if x%x!=0 :
            return True
        else:
            return False


#2

why would you convert to string? here:

    if x=="1" or x=="0":
        return False
    elif x=="2"or x=="3":

just make 0, 1, 2 and 3 integers

here:

if x%x!=0

please explain this condition.

x%x is like doing: 5%5, the remainder will always be zero for this condition, so the condition always evaluates to false, so else runs, so False is returned, the function end (for the function to end, the loop needs to break, so currently your loop makes only one iteration)


#3

Okay, so I don't know why I made that mistake but even though I have fixed everything and tried to figure out the mistake but it still won't work. the code now reads;

def is_prime(x):
    if x==1 or x==0:
        return False
    elif x==2 or x==3:
        return True
    x=str(x)
    for num in range(2,(int(x)-1)):
        x=int(x)
        num=num
        if x%num==0 :
            return False
    else:
        return True

But with the correct indentations.


#4

negative numbers are not prime numbers, maybe put this in your if case which currently cover 0 and 1


#5

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