In this Python example tutorial, we are going to write Python program to print prime numbers in an intervals.
To understand this example you should have basic knowledge of following Python tutorials.
- Python if statement.
- Python for loop.
- Python function.
- Python break statement.
- Python continue statement.
Before going to further this tutorial, we will know about what exactly is prime number?
Headings of Contents
What is Prime Number?
A prime number is a natural number that is greater than 1 and can not be formed by multiplying two smaller natural numbers or in other words, a prime number is a natural number that is exactly divisible by 1 and itself.
1, 3, 5, 7, 11, 13, etc are the example of prime numbers because they do not have any factor but 4, 6, 8, etc are the not prime numbers they have factors.
Example:
# Take input from user
num1 = int(input("Enter first number:- "))
num2 = int(input("Enter second number:- "))
# By default
#num1 = 13
#num2 = 57
print(f"prime number between {num1} and {num2} are:- ", end = ' ')
for i in range(num1, num2 + 1):
if i > 1:
for num in range(2, i):
if i % num == 0:
break
else:
print(i, end= ' ')
Input:
Enter first number:- 12
Enter second number:- 39
Output:
prime number between 12 and 39 are:- 13 17 19 23 29 31 37
Example:
Program to print prime numbers between two numbers using function.
# To take input from user
x = int(input("Enter first number:- "))
y = int(input("Enter second number:- "))
# By default
x = 13
y = 57
# python function to print prime numbers
def primeNumber(num1, num2):
for i in range(num1, num2 + 1):
if i > 1:
for num in range(2, i):
if i % num == 0:
break
else:
print(i, end= ' ')
# call the function
primeNumber(x, y)
Input:
Enter first number:- 12
Enter second number:- 67
Output:
13 17 19 23 29 31 37 41 43 47 53 59 61 67
Python program to print prime numbers from 1 to 100
Print all the prime numbers from 1 to 100. Here we have by default assigned two numbers 1 and 100. You can ask it from the user also.
Example:
#Assign 1 to num1 and 100 to num2
num1 = 1
num2 = 100
#print the result
print(f"prime number between {num1} and {num2} are:- ", end = ' ')
#python code to print prime numbers
for i in range(num1, num2 + 1):
if i > 1:
for num in range(2, i // 2):
if i % num == 0:
break
else:
print(i)
Output:
Prime number between 1 and 100 are:- 2 3 4 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
Conclusion
In this article, you have learned all about how to write a python program to print prime numbers between two numbers using various python examples.
This is a very basic python example, If you are just entering Python programming, Then this type of Python program help you to enhance your programming logic thinking skills.
To learn this type of Python interesting example, follow our Python tutorial. If you like this article, please share and keep visiting for further Python examples.
Reference:- Python