Why won't this code Return properly? (6.is_prime)


#1

The program says that the function fails on is_prime(0), because it returns None when it should return False.

Now, I've gotten better code from the forum already, but I'm genuinely curious just what's wrong with this code to make it fail to return anything.

def is_prime(number):
    i = 2
    while i < (number - 2):
        if i % number == 0:
            return False
        elif number == 0:
            return False
        i += 1
        if i >= number:
            return True

#2

Let's say number is 9. Now step through your algorithm.

number: 9
i:      2
2 % 9:  2
i:      3
3 % 9:  3
i:      4
4 % 9:  4
i:      5
5 % 9:  5
i:      6
6 % 9:  6
i:      7
exit loop

As we see, i is never equal or greater than number.

There is definitely something amiss with the modulo expressions.

Now consider when number is zero. Even with subtracting 2 from number, i is not less than 0; hence, return is None.

So a cursory check of the code turns up errors in the logic. Something to re-visit and sort out, one must conclude?


#3

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