Is Prime


#1



I have NO idea why this isn't working... I thought my logic would be fine here but it returns None...


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


#2

I fixed it! I just removed the else and put the return True after the for loop ran its course! Sorry for the inconvenience!


#3

Yours was a common mistake and one that has thousands of topics to show for it. I am glad that you found your way out of it and made the connection. It is commendable. Kudos.

Happy coding!


#4

If you get rid of the else, and put return true under the for loop doesn't that mean it will return true after running through the if statement or does it stop after the if? I'm confused :expressionless:


#5

Anything that makes it to the last line is Prime. That's the objective once we elliminate all the non-primes.

The key is to let the loop complete without interuption. A match in the loop will cause a False return. If none of these happen, then the only thing left is True.


#6

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