Check if a number is a prime Python

By: On:

In this Python tutorial, we will check if a number is a prime in python and also we will print all prime numbers in an interval python.

Check if a number is a prime python

Now, let us see how to check if a number is a prime in Python. Prime numbers is a whole number which is divisible by 1 and itself.

Example:


number = 17
if number > 1:
for a in range(2, number):
if (number % a)==0:
print(number, "is not a prime number")
break
else:
print(number, "is a prime number")

After writing the above code (check if a number is a prime python), Ones you will print “number” then the output will appear as a “17 is a prime number“. Here, the range() will search from 2 to number -1.

You can refer to the below screenshot to  check if a number is a prime python.

Check if a number is a prime python
Check if a number is a prime python

This is how we can check if a number is a prime python

Print all prime numbers in an interval python

In python, to print all prime numbers in an interval, we use the range and display all prime numbers in that interval.


Example:

lower = 100
upper = 150
print("print number in an interval", lower, "and", upper, "are:")
for number in range(lower, upper + 1):
if number > 1:
for a in range(2,number):
if (number % a) == 0:
break
else:
print(number)

After writing the above code (print all prime numbers in an interval python), Ones you will print “number” then the output will appear as a “101 103 107 109 113 127 131 137 139 149”.

Here, the range() will start from 100 and it will check till 150 and all the prime numbers between them will be printed.

You can refer to the below screenshot to print all prime numbers in an interval python.

Print all prime numbers in an interval python

This is how we can print all prime numbers in an interval python.


You may like following Python tutorials:

In this tutorial, we discussed check if a number is a prime in python, and also we have seen how to print all prime numbers in an interval python.

Leave a Comment