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.
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.
This is how we can print all prime numbers in an interval python.
You may like following Python tutorials:
- Python pip is not recognized as an internal or external command
- Python convert tuple to list
- What does the percent sign mean in python
- Python built-in functions with examples
- Get current directory Python
- Syntaxerror return outside function python
- Remove character from string Python
- Python if else with examples
- Python TypeError: ‘list’ object is not callable
- Python Array with Examples
- Function in Python
- Python exit command
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.
Python is one of the most popular languages in the United States of America. I have been working with Python for a long time and I have expertise in working with various libraries on Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… I have experience in working with various clients in countries like United States, Canada, United Kingdom, Australia, New Zealand, etc. Check out my profile.