How to Check If a Number is Prime in Python

The prime number in mathematics is a number greater than 1 that cannot be exactly divided by any whole number other than itself and 1.

How to Check If a Number is Prime in Python

To check if a number is prime in Python, use a for loop and the % operator that checks if the number is divisible by any other number from 2 to given_num-1. It is prime if the number is not divisible by any of these numbers.

def is_prime(num: int) -> bool:
  # Check if num is less than 2, which is not prime
  if num < 2:
    return False

  # Check if num is divisible by any number from 2 to num-1
  for i in range(2, num):
   if num % i == 0:
     return False

  # If the loop completes without finding a divisor, num is prime
  return True


num = 19

if is_number_prime(num):
 print(f"{num} is a prime number.")
else:
 print(f"{num} is not a prime number.")

Output

19 is a prime number.

You can see that 19 is a prime number. That’s why the is_number_prime() function returns True.

You can then use the is_number_prime() function to check if a number is prime by calling it and passing it as an argument.

Let’s check for the “21” number. The 21 is not a prime number. Let’s check by the program.

num = 21

if is_number_prime(num):
 print(f"{num} is a prime number.")
else:
 print(f"{num} is not a prime number.")

Output

21 is not a prime number.

That’s it. We successfully checked if the given number is prime programmatically in Python.

Remember that this approach is simple and easy to understand, but it can be slow for larger numbers because it checks all numbers from 2 to num-1.

There are more efficient algorithms for checking if a number is prime, such as the Sieve of Eratosthenes, which can be used for higher performance.

That’s it for this tutorial.

Further reading

Find prime numbers in Python range

Leave a Comment