A prime number is a number that is only divisible by 1 and itself. With the power of Python programming, we can easily determine if any given number is a prime number or not. Furthermore, we can also find all prime numbers within a given range of numbers, such as from 2 to N. In this article, we will show you how to write these two programs using Python programming, making it easy for you to understand and implement prime numbers in your projects.
Finding a number a prime number or not?
# primeornot.py
# Below function returns true if number is prime number.
def isPrime(num):
if num < 2:
return False
for val in range(2, num):
# check if given number divisible any number other than 1 and itself.
if num % val == 0:
return False
return True
# 5 is prime number, returns True
print(isPrime(5))
# 8 is non prime, returns False
print(isPrime(8))
# 13 is prime number, return True
print(isPrime(13))
The above program checks given numbers 5, 8, and 13 are prime numbers or not and returns True or False respectively.
# Output
$python primeornot.py
True
False
True
By using the “isPrime()” function, we can easily find a series of prime numbers less than a given input number. The Python program to print this prime number series is straightforward. We use the above-defined “isPrime()” function, loop through all numbers, and check if that number is prime or not. If it is, we print it. The code for this program is simple and easy to understand, making it a useful tool for anyone interested in working with prime numbers and prime number series in Python.
# primeseries.py
# Below function returns true if number is prime number.
def isPrime(num):
if num < 2:
return False
for val in range(2, num):
# check if given number divisible any number other than 1 and itself.
if num % val == 0:
return False
return True
# below function prints all prime numbers which are less than given number.
def primeSeries(num):
for val in range(2, num):
# check if current number is prime or not.
if isPrime(val):
print(val)
# prints all prime numbers less than 20.
primeSeries(20)
The above python program prints all prime numbers series less than the given input number.
# Output
$python primeseries.py
2
3
5
7
11
13
17
19
Hope these above two python prime number programs help you to understand the primary number generation using python. Keep learning!!