Write a Python Program to Print all Prime Numbers in an Interval

In this tutorial, we’ll discuss how to write a Python program to print all prime numbers in an interval.

Prime numbers are those numbers that are divisible only by 1 and themselves.

We can find all prime numbers in a given interval by iterating through all the numbers in that interval and checking whether each number is prime or not.

Let’s start by defining a function that takes two parameters, start and end, which represent the interval we want to find the prime numbers in.

The function will then iterate through all the numbers in the interval and check whether each number is prime or not.

def print_prime_numbers(start, end):
    for num in range(start, end+1):
        # prime numbers are greater than 1
        if num > 1:
            # check for factors
            for i in range(2, num):
                if (num %% i) == 0:
                    break
            else:
                print(num)

The above function first checks if the number is greater than 1 because 1 is not a prime number.

Then it checks for factors by iterating through all the numbers from 2 to num-1.

If any factor is found, the loop breaks and moves to the next number.

If no factor is found, the else statement is executed and the number is printed as it is a prime number.

We can now call this function and pass the start and end values as arguments to find all the prime numbers in that interval.

# find prime numbers between 10 and 50
print_prime_numbers(10, 50)

Output:

11
13
17
19
23
29
31
37
41
43
47

In conclusion, we have seen how to write a Python program to print all prime numbers in an interval.

We defined a function that takes two parameters, start and end, and iterates through all the numbers in that interval to check whether each number is prime or not.

This is a simple yet important program that can be used in various mathematical and scientific applications.