Python function to check if number is prime

Viewed 2459
def is_prime(num):
    lst = []
    if num > 1:
        pass
    else:
        return False
    for number in range(0, 1000000+1):
        if str(num) in str(number):
            continue
        elif str(1) in str(number):
            continue
        elif str(0) in str(number):
            continue
        lst.append(number)
    for x in lst:
        if num % num == 0 and num % 1 == 0 and not(num % x == 0):
            return True
        else:
            return False

print(is_prime(9))

I do not know what is the problem with my code and I cannot find a solution the point of the program is to check whether the number is a prime number or not(prime number is only divisible by 1 and itself). The for loop just doesn't seem to work or something

4 Answers
def isprime(n):
    return (all([False for i in range(2,n) if n % i == 0 ]) and not n < 2)
    
print (isprime(0))
print (isprime(1))
print (isprime(2))
print (isprime(3))
print (isprime(9))
print (isprime(10))
print (isprime(13))

Output:

False
False
True
True
False
False
True

Or:

def isprime(n):

    if n < 2: return False

    for i in range(2, n):
        if n % i == 0:
            return False
    else:
        return True

Line 16-19:

if num % num == 0 and num % 1 == 0 and not(num % x == 0):
    return True
else:
    return False

The first statement, num % num == 0 is finding the remainder when num is divided by num, which is always zero and therefore this statement is always true. num % 1 == 0 is also always true, so your code is equivalent to:

if not(num % x == 0):
    return True
else:
    return False

Which means, in the context of your program, "if the first value in lst is not a factor of num, then num is prime. Otherwise, num is not prime"

This only runs the loop one time and is backwards. Instead, you need to check if one of the numbers in lst is a factor to return False, and if all of the number is lst are not factors, then return True

for x in lst:
    if num % x == 0:
        return False
return True
for x in lst:
    if num % num == 0 and num % 1 == 0 and not(num % x == 0):
        return True
    else:
        return False

This loop can only ever run once, as it's guaranteed to return either true or false at the first iteration. If you find any factors, you want to return False. Otherwise, True.

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

(Also, I'm not sure what was going on with the str shenanigans or the num % num / num % 1 conditions, both of which are always zero. But those should be unnecessary)

Except for 2 itself, you should only check divisibility by odd numbers up to the square root of the value.

Here's a short version:

def isPrime(N): 
    return all(N%p for p in range(3,int(N**0.5)+1,2)) if N>2 and N&1 else N==2
Related