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.
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.
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
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”)
1 2 3 4 5 Loop Terminated! Good Luck Python Lover
801 total views, 3 views today