TJE
TJE

Reputation: 580

How can I fix this code set up to check which numbers are prime numbers?

Here is the code:

def checkIfPrime (numberToCheck):
    for x in range(2, numberToCheck):
        if (numberToCheck%x == 0):
            return False
    return True

It works almost perfectly. The problem I see is that if I check whether zero is a prime number, it says "True." Like this:

>>> checkIfPrime(0)
True

But zero is not a prime number, obviously! What can I do to the code so it will return "False" when I check to see if 0 is a prime number?


EDIT: I see the problem now with my original code. But someone asked me to update my question to show how I attempted, and failed, to check my parameter checkIfPrime to make it so the program would return 'False' when I checked if the number zero is prime. So here's that attempt:

def checkIfPrime (numberToCheck):
    for x in range(2, numberToCheck):
        if (numberToCheck%x == 0):
            return False
        if numberToCheck == 0:
            return False
    return True

Upvotes: 0

Views: 105

Answers (1)

daphtdazz
daphtdazz

Reputation: 8159

Just check it first (and also check for non-integers and 1 at the same time...):

from numbers import Integral
def checkIfPrime (numberToCheck):
    if not isinstance(numberToCheck, Integral):
        return False
    if numberToCheck < 2:
        return False
    for x in range(2, numberToCheck):
        if (numberToCheck%x == 0):
            return False
    return True

Upvotes: 2

Related Questions