Finding Prime Numbers Using Python

Learn python programming in 12 lessons


A prime number is a number that is only evenly divisible by itself and 1 otherwise its regarded as a composite number. To test it a number is prime, you simple take a for loop with a range from 2 to to the number and inside the loop, you divide the number by all those numbers in the range. If you find a number that evenly divides the number, then you break because its obvious the number is not prime.
The for loop would look something like this

for i in range(2,num):          
            if num % i == 0:
                primes = False
                break
            else:
                primes = True

You can easily see that the above loop would take such a long time to execute if you are using a slow computer with little memory. The other trick that you can use to shorten the range of numbers up until the square root of the number. The full code to test if the number is prime using Python can look like this


# This function checks if the number is prime
def prime(num):
    primes = False
    num = int(num)   
         
    if num == 1:
        primes = False       
    elif num == 2:
        primes = True
    else:
        for i in range(2,num):           
            if num % i == 0:
                primes = False
                break
            else:
                primes = True
               
    return primes

Share your thoughts