Why is my is_prime implementation not working?

python

#1



Link to is_prime exercise.


Okay so I feel like I'm really close. I've tested this function out multiple times and it works as far as I can tell, but for some reason is_prime(9) comes back True when it should return False. Can't figure out why. Please help. Also any tips on cutting down the length of the code would be appreciated, I can't help but feel like it's needlessly clunky.


def is_prime(x):
    if x < 2:
        return False
    elif x == 2:
        return True
    elif x == 3:
        return True
    elif x > 2 and x != 3:
        for n in range(2, x-1):
            if x % n == 0:
                return False
            else:
                return True


#2

Get rid of everything that was not in the instructions. Keep the first if, the for and its if; and, return True from the top block of the function. Turf the rest.


#3

def is_prime(x):
    if x < 2:
        return False
    elif x > 2 and x != 3:
        for n in range(2, x-1):
            if x % n == 0:
                return False
            else:
                return True

Like this? Because if x = 2 or x = 3 it returns None instead of True so... ?


#8

here he already told you the answer.

why do you need elif x > 2 and x != 3: ?

  • Keep the first if
  • the for
  • its if;
  • return True from the top block of the function(don't need else)

#9

Hey, sorry you're having some trouble. Let's work this together.

Your code:

def is_prime(x):
    if x < 2:
        return False
    elif x > 2 and x != 3:
        for n in range(2, x-1):
            if x % n == 0:
                return False
            else:
                return True

OK...so, what's a prime number? It's a positive integer greater than 1 that has no positive divisors other than 1 and itself.

Alright, cool. With your current algorithm, you're just making it a bit too complicated.

So, x < 2 is a good starting point and can stay, because all prime numbers are greater than 1, therefore anything less can be considered not prime.

Now, however, the next bits are where you're getting a bit too complicated. Sure, x > 2 is a good condition to check because all prime numbers are greater than 1, but it appears that you're missing 2 itself, which is prime. You are also checking to ensure the number is not 3, but 3 is prime as well.

So what you can actually do is remove that elif altogether, because it is actually breaking your is_prime implementation rather than helping it.

Start your for loop where the elif was beginning, and I think you'll find that things will start ticking the way you'd expect them to.

Extra note: You can move your ending return True to the outside of the for loop, so that it resides at the end of the function.


#10

#12

#13