6/15 is_prime worked... But why?


#1

I read a lot of discussion threads before getting code that worked for is_prime. I had been getting an error for is_prime(0) returning None, is_prime(2) returning True (or None), etc.. I had been reading about inserting a lot of manual conditions (if x < 2:, if x == 1:, etc.) and using range (2, x) instead of range (2, x - 1), which I didn't always understand and which didn't follow the instructions.

I used the code below which worked, and I can see two things done differently here than what I had been trying: (1) The successful code does not contain an "else" corresponding to the "if n % x == 0:" statement and (2) the "return True" statement is outside any if-loop. Why does this work?

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

#2

this is almost exactly what I have come up with. But I keep getting a syntax error on my else: line.

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

    return True

#3

am i missing something. It just says syntax error and points to else:


#4

I believe that the return True can be outside of the for loop because if the loop does not trigger a False than it goes on to the next element in the function stack. Therefore it isn't necessary to have an else statement. Thats my best assumption. I got it working by the way


#5

I had this...

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

..and it worked, but why?

If "x" is lower then 2 it returns False, that's simple.
However, if the for-loop is started, it calculates every possible divisions.
If that output is equal to 0, then "x" is a prime number.
If it's not and the for-loop is finished, the function returns True, because it's a prime number.

I hope this is useful. Enjoy.