Print All Prime Numbers in a Range Using Python

(Last Updated On: 06/01/2023)

Want to know how to find all the prime numbers within an interval in Python? In this guide, we’ll break down the code step by step and explain exactly what is happening so that you can easily use it yourself. Let’s get started!

Python Program to Print Prime Numbers in a Range

# Python program to print all prime numbers in the given range

num_from = 20
num_to = 50

prime_nums = [];

for num in range(num_from, num_to + 1):
   if num > 1:
       for i in range(2, num):
           if (num % i) == 0:
               break
       else:
           prime_nums.append(num)


print("List of prime numbers within range", num_from, "to", num_to, "are:", prime_nums)

Output:

List of prime numbers within range 20 to 50 are: [23, 29, 31, 37, 41, 43, 47]

Understand the Concept of Prime Numbers.

Prime numbers are a special type of number that can only be divided by itself and one. For example, the prime numbers 7 and 11 have no other divisors except for 1 and themselves. This makes them useful for cryptography and other security-related applications as they can be more easily identified than non-prime numbers.

Use an Iterative Loop to Check for Prime Numbers.

To find all the prime numbers in a given interval, we can use an iterative loop. We start at the lower end of the range and then check each number, in turn, to see if it is prime or not. If a number is found to be prime, we add that number to our list of all primes in the interval. This process is repeated until the upper bound of the range has been reached; at which point, all prime numbers within the given range should have been found.

Leave a Reply

Your email address will not be published. Required fields are marked *