Python Program to Check Prime Number [With Code & Output]

Prime numbers are quite essential in different types of mathematics and also in programming. Whether you're any of the ones who are preparing for different interviews, cracking different coding rounds, or even simply learning the Python coding language, checking for different sets of prime numbers is a common and also quite essential and crucial task.

Blogging Illustration

Python Program to Check Prime Number [With Code & Output]

image

In this blog, we’ll explore different types of areas like :

  • What is a prime number, and give examples of the same?
  • Why check for the condition of prime numbers?

Python source code programs to check for different types of prime numbers using:

Basic types of methods
  • For loop condition and examples
  • While loop with condition and examples
  • Function category of the approach
  • List comprehension phase
  • Sieve of Eratosthenes (advanced)
Output examples

Optimization tips are some of the areas majorly observed.

Let’s dive into the ocean of this!

What is a Prime Number, and give some examples for the same?

A prime number is one of the numbers that is greater than 1 and has no positive divisors other than 1 and itself.

Examples of prime numbers set:

2, 3, 5, 7, 11, 13, 17, 19, 23...

Note: 1 is not at all a prime number.

Why Check for the Condition of Prime Numbers in Python?

Interview questions of different companies often involve other types of primes.

Cryptography type uses all prime numbers for different encryption algorithms.

Helps in a great number theory and also for other competitive programming.

Method 1: Basic Python Program with source code to check a Prime Number

This is one of the most beginner-friendly methods that is built using a for loop.

Program source Code:
                            num = int(input("Enter a number: "))

                            # Prime numbers are greater than 1
                            if num > 1:
                                # check for factors
                                for i in range(2, num):
                                    if (num % i) == 0:
                                        print(num, "is NOT a prime number")
                                        print(i, "times", num//i, "is", num)
                                        break
                                Else:
                                    print(num, "is a PRIME number")
                            # if the input number is less than or equal to 1
                            Else:
                                print(num, "is NOT a prime number")

                            Output for the above program:

                            Enter a number: 7
                            7 is a PRIME number

                            Enter a number: 12
                            12 is NOT a prime number
                            3 times 4 is 12

                        

Method 2: Program source code by using a while Loop

Let’s implement this type of program with the same logic with a while loop.

Program source Code:
                           num = int(input("Enter a number: "))
                            i = 2
                            is_prime = True

                            if num > 1:
                                while i < num:
                                    if num % i == 0:
                                        is_prime = False
                                        break
                                    i += 1

                                if is_prime:
                                    print(num, "is a PRIME number")
                                Else:
                                    print(num, "is NOT a prime number")
                            Else:
                                print(num, "is NOT a prime number")

                        
Method 3: Optimized Prime Check program source code (√n Approach)

To reduce all the time complexity issues, we can only check up to the square root of the number here.

Program source Code:
                           import math

                            def is_prime(num):
                                if num <= 1: return false for i in range(2, int(math.sqrt(num)) + 1): if num % 0: true n='int(input("Enter' number: ")) is_prime(n): print(n, "is a prime number") else: not ⏱ time complexity: o(√n) instead of o(n) < pre>
                    
Method 4: Program source code Using a Function (Reusable Code)

You can easily modularize the source code and make it reusable for the next case.

Program source Code:
                           def check_prime(n):
                            if n <= 1: return false for i in range(2, n): if n % 0: true # driver code number='int(input("Enter' number: ")) check_prime(number): print(f"{number} is a prime number.") else: not < pre>
                    
Method 5: Program source code for One-Liner Prime Check Using List Comprehension

Great for all other types of compact Python programs.

Program source Code:
                          n = int(input("Enter a number: "))
                            print("PRIME" if n > 1 and all(n % i != 0 for i in range(2, n)) else "NOT PRIME")
 
                        

Best suited and Ideal for quick implementations in all types of coding tests.

Method 6: Program source code for Sieve of Eratosthenes (Advanced, for multiple primes)

This is one of the fastest methods used to generate all types of primes up to n.

Program source Code:
                           def sieve_of_eratosthenes(limit):
                                primes = [True for _ in range(limit+1)]
                                p = 2
                                while p * p <= limit: if primes[p]: for i in range(p*p, limit+1, p): primes[i]="False" p +="1" print("prime numbers up to", limit, "are:") range(2, limit+1): primes[i]: print(i, end="" ) # driver code n='int(input("Find' all primes to: ")) sieve_of_eratosthenes(n) < pre>
                    
Output for the above program:

Find all primes up to: 30

Prime numbers up to 30 are:

2 3 5 7 11 13 17 19 23 29

Comparing Time Complexities of different loops
MethodTime complexity
Basic for-loopO(n)
Optimized √n methodO(√n)
Sieve of EratosthenesO(n log log n)

Bonus tips: Prime Numbers in a Range

Want to find all primes between two particular numbers?

✅ Code:
                           def is_prime(num):
                            if num <= 1: return false for i in range(2, int(num**0.5)+1): if num % 0: true start='int(input("Enter' of range: ")) end='int(input("Enter' print(f"prime numbers between {start} and {end} are:") n range(start, end+1): is_prime(n): print(n, ) < pre>
                    
Problem using Library (External)

For a large-scale set of applications, Python can easily use libraries that will help you to simplify things.

Program source Code:

From sympy import isprime

                           num = int(input("Enter number: "))
                            if isprime(num):
                                print(f"{num} is a PRIME number")
                            Else:
                                print(f"{num} is NOT a prime number")

                        
Installation request:

pip install

Handling Different Edge Cases
InputOutput
-5Not a prime
0Not a prime
1Not a prime
2Prime (only even prime)
997Prime
Real-World type of Applications of Prime Numbers

1. Cryptography type: RSA algorithm-based

2. Hashing category: In hashing type of functions and other data structures

3. Random set of Number Generation

4. Computer Networks: IP security and encryption algorithms

Conclusion:

Prime number is often used for checking is one of the classic problems in both types of math and programming. In the Python programming language, you can easily start with all basic loops, move to other efficient functions, or even use some of the external libraries for a large set of numbers. Understanding all these different methods will not only sharpen your kind of logic but also help you improve your coding skills and performance in some competitive exams and interviews.

Summary
ApproachBest Use Case
Basic for loopBeginners
While loopLearning logic flow
Function approachReusability
Optimized √n logicBetter performance
One-linerQuick tests or scripts
Sieve of EratosthenesFinding multiple primes
Sympy libraryBuilt-in large number check
Suggested Practice:

Try writing your versions of:

1-Prime checker using recursion
Program source code :
                           def is_prime_recursive(n, i=2):
                            if n <= 2 2: return true if n="=" else false % i="=" 0: *> n:
                                return True
                            return is_prime_recursive(n, i + 1)

                        # Driver code
                        num = int(input("Enter a number: "))
                        if is_prime_recursive(num):
                            print(f"{num} is a PRIME number")
                        Else:
                            print(f"{num} is NOT a prime number")

                        
Output :
                            Enter a number: 17
                            17 is a PRIME number

                        
2-Program to count primes in a range
Program source code :
                           def is_prime(n):
                            if n <= 1: return false for i in range(2, int(n**0.5)+1): if n % 0: true def count_primes_in_range(start, end): count="0" num range(start, end + 1): is_prime(num): # driver code start='int(input("Enter' range start: ")) end: < pre>
                    

print(f"Total prime numbers between {start} and {end}: {count_primes_in_range(start, end)}")

Output :
                           Enter range start: 10
                            Enter range end: 50
                            Total prime numbers between 10 and 50: 10

                        
3-First N prime numbers
Program source code :
                           def is_prime(n):
                            if n <= 1: return false for i in range(2, int(n ** 0.5)+1): if n % 0: true def first_n_primes(n): primes="[]" num="2" while len(primes) < n: is_prime(num): primes.append(num) +="1" # driver code the value of ")) print(f"first {n} prime numbers are:") print(first_n_primes(n)) pre>
                    
Output :
                           Enter the value of N: 10
                            The first 10 prime numbers are:
                            [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]

                        

4-Prime palindrome checker

Program source code :
                          def is_prime(n):
                            if n <= 1: return false for i in range(2, int(n ** 0.5)+1): if n % 0: true def is_palindrome(n): str(n)="=" str(n)[::-1] is_prime_palindrome(n): is_prime(n) and is_palindrome(n) # driver code num='int(input("Enter' a number: ")) is_prime_palindrome(num): print(f"{num} is prime palindrome") else: not < pre>
                    
Output :
                           Enter a number: 131
                            131 is a PRIME PALINDROME

                        

Enroll in a Python training course in Noida and get the learning that you have ever wanted.

Placed Students

Our Clients

Partners

Uncodemy Learning Platform

Uncodemy Free Premium Features

Popular Courses