In this simple python program, we need to display prime numbers of a range. It's a beginner-level python program.
To understand this example, you should have knowledge of the following Python programming topics:
In this python program example, we need to print all the prime numbers between two numbers given by the user. To understand the program clearly, we need to check what is mean by a prime number? A number with only 2 divisors, which are 1 and that number itself, is called a Prime number.
So in this python example, we need to check every number in a range if it's prime or not. To achieve that, we use two
for loop using the
range function. The
range() function is used with the for loop in python, the
range() function is used to loop through a specified number of times.
Range() function in python has the default value starting from zero and increment by 1 every time and ends when it reaches a specified value. For example, if we use 'for x in range(3)' then the loop starts from zero as default and up to 2. please note the loop ends at 2, not 3.
This python program uses two
for loop nested like the outer for loop starts from the lower number up to the upper range. Then inside the loop, we check for the number is greater than zero; if it is true, we start the inner
for loop from range 2 to that number. Inside the inner loop, we use the Mod operator and check that is equal to zero using
if condition in python; if it is equal to zero, break the loop, and it is not a prime.
Else print the number as prime. Let us break the code
STEP 1: Accept the user's values for the lower and upper value using input function in python and convert into an integer using int datatype.
STEP 2: Start the outer
for loop using the range from lower value to upper value +1. We use up+1 to reach the up value.
STEP 3: Add an
if condition to check if the number is positive or not.
STEP 4: Start the inner for loop to check every number prime or not by using the mod operator
STEP 5: If the number is divisible by any number, break the loop. Else print the number.
#Take the input from the user: low = int(input("Enter lower range: ")) up = int(input("Enter upper range: ")) for n in range(low,up + 1): if n > 1: for i in range(2,n): if (n % i) == 0: break else: print(n)
Enter low range: 2 Enter up range: 10 2 3 5 7