Is_prime


#1



i am stuck on is_prime exercise

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


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


I think it is because i am not returning the new value assigned to the variable a but I'm not sure on how to proceed further
Here's my code


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


#2

This is a novel approach we don't see very often. Did you try,

if a != 0:

?
Give it a try and we can look at this some more if it still doesn't work.

What if x is negative?

if x < 2:

will cover all the cases less than 2.


#3

def is_prime(x):
    a=0
    if x<2:
        return False
    else:
        for i in range(2,x-1):
            a=a+ (x%i)
        if a!=0:
            return False
        else:
            return True

It still shows the same error :slight_frown:
: Oops, try again. Your function fails on is_prime(4). It returns True when it should return False.


#4

So then there is a wrinkle in your logic. Take out a pencil and a piece of paper. Start with the number 4 and run the loop (in your head) and note the values that are added to a.

2..3 should be the iterations, but your range is set too low. Instead of,

 for 2,  a += 0
 for 3,  a += 1

your code only runs,

for 2,  a += 0

so ends up returning True. Set the range to (2, x) and try again. We won't know if this logic is sound until it does not fail.


#5

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