October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk3 min

Prime Number Program in Python: Check a Number with a Function

A reusable Python function to test whether an integer is prime, with exact square-root bounds, clear examples, and guidance on when to use a sieve instead.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use a function that returns True when an integer is prime and False otherwise. This version rejects values below 2 and tests divisors only through the exact integer square root.

Python prime-number program using a function

from math import isqrt

def is_prime(n):
    if n < 2:
        return False

    for divisor in range(2, isqrt(n) + 1):
        if n % divisor == 0:
            return False

    return True

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

For example, entering 9 prints 9 is not prime; entering 7 prints 7 is prime. The examples follow directly from the function’s logic.

As an Amazon Associate I earn from qualifying purchases.

How the function decides whether a number is prime

Reject numbers below 2

A prime is an integer greater than 1 whose only positive divisors are 1 and itself. The first condition handles zero, one, and negative integers before the loop. Without it, the loop might not run for a small input, and the function could incorrectly reach return True.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Test divisibility with the remainder operator

For an integer candidate divisor, n % divisor == 0 means the division leaves no remainder. Python defines % as the operator that yields the remainder from dividing the first argument by the second (Python language reference).

Stop at the square root, including the endpoint

If a number has a factor greater than its square root, it must also have a paired factor below the square root. So it is enough to test divisors from 2 through that boundary. Python’s range excludes its stop value, which is why the code uses isqrt(n) + 1 as the stop.

math.isqrt returns the floor of the exact square root for a nonnegative integer and has been available since Python 3.8, according to the Python 3.14.8 math documentation. Using it avoids relying on a floating-point square root for the loop bound.

What happens with small inputs and perfect squares

  • 2 and 3 pass: neither has a candidate divisor in the loop.
  • 4 fails at divisor 2.
  • 9 fails at divisor 3. Adding 1 to the range stop ensures the square-root endpoint is tested.
  • 1 and negative integers return False immediately.

A common boundary bug is writing range(2, int(n ** 0.5)). Since the stop is excluded, that form can skip the square root itself—for example, divisor 3 for 9. The explicit inclusive bound in the program avoids that error.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Why the function returns a Boolean

is_prime(n) answers the calculation by returning a Boolean. The input and print statements handle interaction separately, so other code can call the function without printing from inside it. When a divisor is found, return False ends the search immediately; if the loop finishes without finding one, the number is prime.

When to use a different prime-number method

One number: trial division

This function uses trial division, a readable choice when the task is to classify one integer. Its square-root bound reduces the number of checks, but trial division becomes impractical for extremely large integers.

Every prime up to a limit: a sieve

If the goal is to generate all primes up to a maximum, use a Sieve of Eratosthenes rather than calling this function for every candidate. A sieve marks composite numbers across the range and collects the unmarked values; Al Sweigart’s chapter on finding and generating prime numbers presents this approach for range generation.

Very large integers

For extremely large values, the same chapter introduces Rabin–Miller testing rather than suggesting trial division scales indefinitely. The classroom function is for straightforward integer checks; it does not establish cryptographic suitability.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Further reading

Al Sweigart’s Cracking Codes with Python includes a chapter on testing and generating prime numbers, with trial-division and sieve approaches: Finding and Generating Prime Numbers.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.