Sabih Hasan Sabih Hasan - 16 days ago 6
Python Question

Adding a number to the list if it passes the conditions in another function

so I've written a function which checks if a number is a prime

def prime_checker(prime):
limit = int(math.sqrt(prime))
x = 2
while x <= limit:
if prime % x != 0:
x += 1
if x == limit:
print("%d is prime" % prime)
return True
else:
print("%d Not a prime" % prime)
return False

prime_checker(199)


Now I want to create a function which tests numbers with prime_checker method and append this number to a list if it is prime. My attempt for it is:

def prime_counting():
list_of_primes = []
for x in range(10):
if prime_checker(x) == True:
list_of_primes.append(x)
print(list_of_primes)

prime_counting()


However, this doesn't work. Is there any way to fix this?

Answer

Your prime checker does not work in some cases. Try

def prime_checker(prime):
    limit = int(math.sqrt(prime))
    for x in range(2, limit + 1):
        if prime % x == 0:
            return False
    return True