Python Program Prime Between Two Numbers

By | May 15, 2022

Python Program Prime Between Two Numbers

In this Python programming tutorial we shall learn to write and execute a Python program to print all the prime numbers between the two givenĀ  numbers.

Program statement:

Write a Python program to input two numbers and print all the prime numbers between these two numbers.

Actually we want to print all prime numbers between a given interval or range. For example if we enter 1 and 10. the output of the program will be 3, 5, 7.

Display All Prime Numbers Between Two given Numbers Enterd by the user

Simple Definition of a Prime Number and Composite Number

A positive integer greater than 1 which has no other factors except 1 and the number itself is called a prime number.

Examples of Prime Numbers and Composite Numbers

For example, 2, 3, 5, 7, 11, 13 etc. are prime numbers as they do not have any other factors. But 4 is not a prime number since, 2 x 2 = 4. that is it has a factor =2 other than 1 and itself. Such number is called a composite number. Other examples f composite number are 4, 6, 8, 9, 14, 15, 18 etc.

The Logic of Python Program Prime Numbers Between Two Numbers

1: We shall use a for loop to get all the numbers between the given two numbers or range.
2: An if statement will check for each number if it has any factor / divisor between 1 and itself.
3: If the given condition is true, then the number is not prime, and it will move to the next number.
4: If there is no such factor or divisor then it is the prime number, and the program will print it and check for the next number.
5: The loop will run from lower number to upper number in the given range or interval.

Code of Python Program for Prime Numbers in Range

# Write a Python program to input two numbers
# and print all prime numbers between these
# two numbers , for example if numbers entered
# are 1 and 10 the output will be 3,5,7
num1 = int(input ("Enter the First Number(Lower Range Value):"))  
num2 = int(input ("Enter the Second Number:(Upper Range Value)"))  
print ("The Prime Numbers between\n",num1," and ",num2," are: ")  
for n in range (num1, num2 + 1):  
    if n > 1:  
        for i in range (2, n):  
            if (n % i) == 0:  
                print (n) 

Special Syntax of for loop with else keyword

The else keyword in a for loop specifies a block of code to be executed when the loop is finished. The else block will NOT be executed if the loop is stopped by a break statement.
Print all numbers from 1 to 5, and print a message “Loop Terminated! Good Luck Python Lover” when the loop has ended:
for num in range(1,6):
print(“Loop Terminated! Good Luck Python Lover”)


Loop Terminated! Good Luck Python Lover

 801 total views,  3 views today

Leave a Reply

Your email address will not be published.