Python Program to Print all Prime Numbers in an Interval

Posted in

Python Program to Print all Prime Numbers in an Interval
vinaykhatri

Vinay Khatri
Last updated on April 26, 2024

    Python is one of the easiest and fun programming languages to learn. If you are also learning Python, you may find it an interesting exercise to print all the prime numbers that exist in a specified range. Here in this Python tutorial, we will guide you with a simple Python program that asks the user to input two numbers that specifies the range and print all prime numbers that exist between the two numbers.

    Python Topics Required to Create the Program

    Note: 1 is not a prime number. Prime numbers are only positive integer values.

    Important Steps to Develop the Program

    • First, we will ask the user to enter two numbers that represent the lower and upper range of the interval.
    • Using the int() function we will convert the entered value into an integer value.
    • We need to use the nested loop, where the outer loop goes through each number from lower limit to upper limit and the inner loop check if the outer loop number is prime or not.

    Python Program to Print all Prime Numbers in an Interval

    Python Code:

    lower =int(input("Enter the lower limit or Number: "))
    upper =int(input("Enter the upper limit or Number: "))
    
    for num in range(lower, upper + 1):
        if num > 1:
            #this for loop check if the num value is prime or not
            for i in range(2, num):
                if (num % i) == 0:
                    break
            else:
                print(num)

    Output 1:

    Enter the lower limit or Number: 800
    Enter the upper limit or Number: 900
    809
    811
    821
    823
    827
    829
    839
    853
    857
    859
    863
    877
    881
    883
    887

    Output 2:

    Enter the lower limit or Number: 1
    Enter the upper limit or Number: 100
    2
    3
    5
    7
    11
    13
    17
    19
    23
    29
    31
    37
    41
    43
    47
    53
    59
    61
    67
    71
    73
    79
    83
    89
    97

    People are also reading:

    Leave a Comment on this Post

    0 Comments