Python Program – Print Prime Numbers between Given Two Numbers

Print Prime Numbers between Given Two Numbers

In this program, we define a function findPrimes() to return a list of prime numbers present in between the two numbers m, n.

Inputs to the function

m, n where m>0, n>0 and m < n

Program

We write findPrimes() function that takes m and n as parameters, and returns a list of prime numbers in the range [m, n).

Python Program

def findPrimes(m, n):
    primes = []

    for k in range(m,n):
        #check if k is a prime number
        i = 2
        isPrime = True
        
        while i < (k / i):
            if k % i == 0:
                isPrime = False
                break
            i += 1

        #if k is a prime number, append it to result list
        if isPrime:
            primes.append(k)

    return primes


m = 5
n = 25
result = findPrimes(m, n)
print(result)
Run Code Copy

Output

[5, 7, 9, 11, 13, 17, 19, 23]

Summary

In this tutorial of Python General Programs, you learned how to print the prime numbers present in between two given numbers.

Code copied to clipboard successfully 👍