VOOZH about

URL: https://www.geeksforgeeks.org/python/python-program-to-check-whether-a-number-is-prime-or-not/

⇱ Check Prime Number in Python - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check Prime Number in Python

Last Updated : 16 May, 2026

Given a positive integer n, the task is to check whether the number is prime or not in Python. A prime number is a number greater than 1 that has exactly two factors, 1 and itself. For Example:

Input: n = 29
Output: Prime Number

Input: n = 10
Output: Not a Prime Number

Let’s look at the methods below to check for a prime number.

Using flag variable

The program checks whether the number is divisible by any value from 2 to √n. If any divisor is found, the number is not prime; otherwise, it is prime.


Output
True

Explanation:

  • n <= 1 checks numbers that are not prime. Loop runs from 2 to √n.
  • n % i == 0 checks divisibility and prime becomes False if a divisor is found.

Using isprime() method

This method uses the isprime() function from the SymPy library to check whether a number is prime.

Output

True

Explanation:

  • isprime(n) checks whether n is prime.
  • Function returns True for prime numbers and False otherwise.

Using Sieve of Eratosthenes

This method creates a list of numbers and marks multiples of each number as non-prime until the target number is reached.


Output
True

Explanation:

  • s stores prime status of numbers.
  • Multiples of each number are marked False.
  • s[n] determines whether the number is prime.

Using Recursion

This approach checks divisibility recursively by reducing the divisor value in each function call.


Output
True

Explanation:

  • Function checks whether n is divisible by i. If divisible, it returns False.
  • Otherwise, recursion continues with i - 1. If no divisor is found, it returns True.

Related Articles:

Comment