How to Check If a Number Is Prime in Python

In mathematics, a prime number is a natural number greater than 1 that has exactly two distinct positive divisors: 1 and the number itself. In simple terms, a prime number cannot be formed by multiplying two smaller natural numbers together.

The sequence of prime numbers begins with 2, 3, 5, 7, 11, 13, 17, 19, 23, and 29. Any natural number greater than 1 that has more than two positive divisors is known as a composite number. For example, 12 is a composite number because it can be divided evenly by 1, 2, 3, 4, 6, and 12.

Meanwhile, the numbers 0 and 1 occupy a special category in number theory. They are classified as neither prime nor composite because 1 has only a single positive divisor, while 0 can be divided by any non-zero integer without leaving a remainder.

A few fascinating mathematical properties make prime numbers unique. First, the number 2 is both the smallest prime number and the only even prime number in existence. Every other even number is automatically divisible by 2, giving it at least three divisors and making it a composite number. 

Second, around 300 BCE, the ancient Greek mathematician Euclid proved that there are infinitely many prime numbers. No matter how large a prime number becomes, there will always be an even larger prime number beyond it. Although prime numbers appear frequently among smaller digits sometimes just two numbers apart, such as 11 and 13 or 17 and 19 the gaps between consecutive primes generally grow wider as numbers increase.


Checking whether a number is prime is a great way to practice conditional statements, loops, and Python's unique for-else syntax. In the video below, we walk through a clean, rock-solid prime checker script from scratch without importing any external libraries.

Python Code: Prime Number Checker

You can run this code directly in any Python environment by changing the value assigned to number:

# Store the target number in a variable
number = 47

# Check if the number is 0 or 1
if number == 0 or number == 1:
    # 0 and 1 are not prime numbers by definition
    print(f"{number} is not a prime number")

# Check numbers strictly greater than 1
elif number > 1:
    # Hunt for factors from 2 up to number - 1
    for i in range(2, number):
        # Use the modulo operator to detect an even division
        if (number % i) == 0:
            # Finding any factor proves the number is composite
            print(f"{number} is not a prime number")
            # Show the exact math behind the factor
            print(f"{i} times {number // i} is {number}")
            # Exit the loop immediately to save computing power
            break
    # Python's for-else syntax runs only if no break occurred
    else:
        print(f"{number} is a prime number")

# Handle edge cases like negative inputs
else:
    print(f"{number} is not a prime number")

Sample Output

47 is a prime number

(Note: If you test with a composite number like 12, it outputs: 12 is not a prime number followed by 2 times 6 is 12.)

How This Script Works

  • Handle 0 and 1: By mathematical definition, 0 and 1 are not prime numbers. The initial if statement catches these inputs right away.

  • Hunt for Factors with Modulo (%): For numbers greater than 1, a for loop checks every potential divisor from 2 up to number - 1. If number % i == 0, it means i divides evenly into number, proving it is composite.

  • Break Early & Use for-else: Once a factor is found, break stops the loop immediately to save computing power. If the loop finishes without hitting break, Python's else block runs and confirms the number is prime.

  • Catch Negative Inputs: The final else statement safely handles negative numbers, confirming they are not prime.

Alternative Approach: Optimizing with Square Root

For very large numbers, you only need to check divisors up to the square root of the number, which makes the script much faster:

import math

number = 47

if number > 1:
    for i in range(2, int(math.sqrt(number)) + 1):
        if (number % i) == 0:
            print(f"{number} is not a prime number")
            break
    else:
        print(f"{number} is a prime number")
else:
    print(f"{number} is not a prime number")


Prime numbers are widely referred to as the building blocks of mathematics because of a core principle called the Fundamental Theorem of Arithmetic. This theorem states that every integer greater than 1 is either a prime number itself or can be represented as a unique product of prime numbers, regardless of the order in which those factors are arranged.

For instance, the number 60 can always be broken down into the exact prime factorization of 2 × 2 × 3 × 5. Beyond pure mathematics, prime numbers play an essential role in modern computing and digital security, forming the mathematical foundation for public-key cryptography systems like RSA that protect online banking, passwords, and cloud communications. Understanding these foundational rules makes it much easier to design logical conditions when writing prime-checking programs.



Have a Python concept you would like broken down next? Drop a comment below or subscribe on YouTube (@programmer_script99) for more bite-sized coding tutorials!

Comments

Popular posts from this blog

🌐🤖 Modi Calls for Inclusive AI, Unveils MANAV Framework

Amazon CodeGuru

☁️ Cloud Services: The Hidden Playground of Cybercriminals