Python Program to Check Prime Number

Python Program to Check Prime Number

22 Aug 2024
Beginner
34.6K Views
22 min read

Python Program to Check Prime Number

Do you know what Prime numbers are? You must have definitely learned them in your schools. A Prime number is a number which is only divisible by 1 and the number itself. But do you know how to use Prime number in Python Programs?

In this Python Tutorial, we'll explore How to calculate Prime number in Python, we will also try checking Prime number in Python using while loop, and much more. Enroll in our Python Certification Training Program right now to learn more about different topics and concepts of Python Programming!

Read More: Top 50 Python Interview Questions and Answers

What is a Prime Number?

A prime number is a number that is only divisible by '1' and itself. In simpler terms, you cannot come up with a prime number by multiplying two smaller natural numbers.

We will now try to explore different ways to check a prime in Python programs.

Basic Program For Checking Prime Number in Python

If you would like to determine if a certain number is prime, you might want to create a simple Python program using Python Compiler that checks for any other divisors except one and the number itself.

def is_prime(num):
    if num <= 1:
        return False
    for i in range(2, int(num**0.5) + 1):
        if num % i == 0:
            return False
    return True

number = int(input("Enter a number: "))
if is_prime(number):
    print(f"{number} is a prime number.")
else:
    print(f"{number} is not a prime number.")

This will involve making a request for your input on a certain number before subjecting it under the mentioned test condition, which causes it to display results as follows.

Output

Enter a number: 7
7 is a prime number.

How do you find the prime number from 1 to 100 in Python?

You can see what numbers are prime numbers in a given range at once as well. This can be done using a loop that will check each number in the given range to see if it is prime.
def is_prime(num):
    if num <= 1:
        return False
    for i in range(2, int(num**0.5) + 1):
        if num % i == 0:
            return False
    return True
primes = []
for num in range(1, 101):
    if is_prime(num):
        primes.append(num)
print(primes)

This will show a full list of all the prime numbers present between 1 to 100.

Output

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

Methods to Check Prime Number in Python

There are several ways through which we can check prime numbers in Python. Let's try to understand each one separately with example programs. But before proceeding further you must be aware of the various Loops in Python, Functions in Python to understand the programs better.

1. Checking Prime Numbers Using Recursion

Recursion functions in Python offer another way to check if a number is prime or not. Let's see how to use them with a simple program in the Python Online Compiler.
def is_prime_recursive(num, divisor=None):
    if divisor is None:
        divisor = num - 1
    if num <= 1:
        return False
    if divisor == 1:
        return True
    if num % divisor == 0:
        return False
    return is_prime_recursive(num, divisor - 1)

number = int(input("Enter a number: "))
if is_prime_recursive(number):
    print(f"{number} is a prime number.")
else:
    print(f"{number} is not a prime number.")

Output

Enter a number: 24
24 is not a prime number.

2. Finding Prime Numbers with a Flag Variable

Using a flag variable can make the logic more clear. A flag will be set by using the flag variable whenever a divisor is found.
def is_prime_with_flag(num):
    if num <= 1:
        return False
    flag = True
    for i in range(2, int(num**0.5) + 1):
        if num % i == 0:
            flag = False
            break
    return flag

number = int(input("Enter a number: "))
if is_prime_with_flag(number):
    print(f"{number} is a prime number.")
else:
    print(f"{number} is not a prime number.")

Output

Enter a number: 6 
6 is not a prime number.
Read More: Python Developer Salary

3. Checking Prime Numbers Using sympy.isprime() method

The 'sympy' library in Python provides a built-in function to check for prime numbers.
def is_prime(num):
    if num <= 1:
        return False
    for i in range(2, int(num**0.5) + 1):
        if num % i == 0:
            return False
    return True

number = int(input("Enter a number: "))
if is_prime(number):
    print(f"{number} is a prime number.")
else:
    print(f"{number} is not a prime number.")

This will also print if the number given by the user is prime or not.

Output

Enter a number: 11
11 is a prime number.

4. Check the Prime Trial Division Method

With the Trial Division Method, the given number is tested against all possible divisors up to its square root.
def is_prime(num):
    if num <= 1:
        return False
    for i in range(2, int(num**0.5) + 1):
        if num % i == 0:
            return False
    return True

number = int(input("Enter a number: "))
if is_prime(number):
    print(f"{number} is a prime number.")
else:
    print(f"{number} is not a prime number.")

Now, we can give a number and see what it does.

Output

Enter a number: 23
23 is a prime number.

5. Checking Prime Numbers Using a While Loop

Using a while loop in Python for checking for prime numbers is another commonly used method.
def is_prime_while(num):
    if num <= 1:
        return False
    i = 2
    while i <= int(num**0.5):
        if num % i == 0:
            return False
        i += 1
    return True

6. Python Program to Check Prime Number Using Math Module

The math module in Python provides helpful functions for mathematical operations.
import math

def is_prime_math(num):
    if num <= 1:
        return False
    for i in range(2, math.isqrt(num) + 1):
        if num % i == 0:
            return False
    return True

number = int(input("Enter a number: "))
if is_prime_math(number):
    print(f"{number} is a prime number.")
else:
    print(f"{number} is not a prime number.")

Output

Enter a number: 22
22 is not a prime number.

7. Python Program to Check Prime Number Using a while loop to check divisibility

'is_prime_while(num)' is a function that checks if 'num' is a prime number. Try this example below in Python Editor to understand it better.
def is_prime_while(num):
    if num <= 1:
        return False
    i = 2
    while i <= int(num**0.5):
        if num % i == 0:
            return False
        i += 1
    return True

# Check if a single number is prime
number = int(input("Enter a number: "))
if is_prime_while(number):
    print(f"{number} is a prime number.")
else:
    print(f"{number} is not a prime number.")

Output

Enter a number: 17
17 is a prime number.

8. Prime Number Generator Using a Generator Function

Generator functions in Python allow you to iterate through prime numbers.
def prime_generator():
    num = 2
    while True:
        if is_prime(num):
            yield num
        num += 1

gen = prime_generator()
for _ in range(10):
    print(next(gen))
Read More: Python Career Opportunities: Is it worth learning Python in 2024?

Prime Factorization

Prime factorization involves identifying the prime factors of a number.
def prime_factors(num):
    i = 2
    factors = []
    while i * i <= num:
        if num % i:
            i += 1
        else:
            num //= i
            factors.append(i)
    if num > 1:
        factors.append(num)
    return factors

number = int(input("Enter a number: "))
print(f"Prime factors of {number} are: {prime_factors(number)}")

It will print out the prime factors of this number

Output

Enter a number: 24
Prime factors of 24 are: [2, 2, 2, 3]

Sieve of Eratosthenes

The algorithm, the Sieve of Eratosthenes, helps to determine the prime numbers less or equal to the specified limit.
def sieve_of_eratosthenes(limit):
    sieve = [True] * (limit + 1)
    sieve[0:2] = [False, False]
    for i in range(2, int(limit**0.5) + 1):
        if sieve[i]:
            for j in range(i*i, limit + 1, i):
                sieve[j] = False
    return [i for i, is_prime in enumerate(sieve) if is_prime]

print(sieve_of_eratosthenes(100))

It will print all the prime numbers up to the given limit of 100.

Output

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
Conclusion
Prime numbers are a key concept in applications related to numbers. If you know all these ways, choosing the right one for your specific program will not be difficult for you. In case you are interested in learning more about such concepts as shown in the Python language specifically, consider taking our Python Certification Course right now!

FAQs

To find a prime number in Python, check if a number is divisible by only 1 and the number itself or not.

To print 1 to 100 prime numbers in Python, use a function that checks and prints all prime numbers between 1 to 100 such as is_prime().

To print 10 prime numbers in Python, you can use a loop and the 'is_prime_while' function.

It is not a prime number as a number is prime if it has two divisors 1 and itself but 1 has only one divisor 1(itself).
Share Article
About Author
Sakshi Dhameja (Author and Mentor)

She is passionate about different technologies like JavaScript, React, HTML, CSS, Node.js etc. and likes to share knowledge with the developer community. She holds strong learning skills in keeping herself updated with the changing technologies in her area as well as other technologies like Core Java, Python and Cloud.

Accept cookies & close this