:Is_Prime" New Coder-in-progress Needs Help


#1


I am new to this community but finding it interesting so far. I just want to understand while my code is throwing up an error message. i will appreciate any help.

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.

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

I will appreciate any help here!


#2

your loop will only run once, either if is true, or else will run, a return statement is reached either way in the first run. The moment return is reached, something gets returned, and the function ends. You want to put return True outside your for loop


#3

Thanks for your prompt response.

Does that mean the problem can't be solved with a built-in-function "range" as I attempted?


#4

It can be, your return True should just be outside the for loop:

for loop:
    if condition:
        return False
return True

Now, the return True is outside your for loop. So now your for loop will run, return False if the number is not a prime. Otherwise, it will reach return True, and return True, the number is a prime


#5

Excellent!! Thanks for this!

It runs correctly now. I need to pay more attention to stuffs like this. Lesson learnt. On to the next!