In this post we'll see a Python program to display prime numbers in the given range. This program helps in understanding usage of nested loops and it also shows a use case where __for loop with else in Python__ can be used.

A number is a prime number if it can be divided either by 1 or by the number itself. So every number with in the given range has to be divided in a loop from 2 till number/2 to check if number is a prime number or not. You only need to run your loop from 2 to N/2, rather than from 2 to N (where N is the current number in the passed range), as no number is completely divisible by a number more than its half. Reducing the iteration to N/2 makes your program to display prime numbers more efficient.

### Displaying prime numbers Python program

def display_prime(lower, upper): for num in range(lower, upper+1): # instead of int(num/2), num//2 (floor division) can also be used for i in range(2, int(num/2)+1): # if number is completely divisible then it # it is not a prime number so break out of loop if num % i == 0: break # if loop runs completely that means a prime number else: print(num) def get_input(): """Function to take user input for display range""" start = int(input('Enter start number for displaying prime numbers:')) end = int(input('Enter end number for displaying prime numbers:')) # prime numbers start from 2 if start <= 1: start = 2 # call function to display prime numbers display_prime(start, end) # start program get_input()

__Output__

Enter start number for displaying prime numbers:40 Enter end number for displaying prime numbers:100 41 43 47 53 59 61 67 71 73 79 83 89 97

That's all for this topic **Python Program to Display Prime Numbers**. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Programs Page

__Related Topics__

**You may also like-**