October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk2 min

Python Program to Find Prime Numbers in a Range

A clear Python program for listing primes between inclusive bounds, with an explanation of divisor checks and the square-root limit.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use trial division to check each number from the lower bound through the upper bound, inclusive. The program below skips values below 2 and tests possible divisors only up to the candidate’s integer square root.

Python program for an inclusive range

This version treats both low and high as included endpoints. Set the two values near the bottom of the code to choose the interval.

import math


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

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

    return True


def primes_in_range(low, high):
    return [n for n in range(low, high + 1) if is_prime(n)]


low = 1
high = 50
print(primes_in_range(low, high))

For the example bounds, the output is:

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]

The list contains primes from 1 through 50; neither endpoint is prime in this example. The helper also handles intervals below 2, and a reversed interval produces an empty list.

How the primality check works

Exclude values below 2

A prime is an integer greater than 1 whose only positive divisors are 1 and itself. Negative numbers, 0, and 1 are therefore not prime. The early if n < 2 check handles them directly.

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

Check divisors only through the square root

The expression n % divisor == 0 detects an even division, so n is composite when it is true for any candidate divisor. The loop only needs to reach the square root: if a number has a factor above its square root, its paired factor is below it. Python’s math.isqrt returns the floor of the exact square root for a nonnegative integer and has been available since Python 3.8.

The + 1 in range(2, math.isqrt(n) + 1) matters because Python’s range excludes its stop value. It ensures the integer square root itself is checked. For example, 25 must be tested for divisibility by 5; omitting that endpoint would incorrectly classify it as prime. If no divisor is found, the function returns True.

Adjusting the bounds and output

Python’s range includes its starting value but excludes its stopping value. The outer loop therefore uses high + 1 to include the requested upper endpoint. To use a half-open interval [low, high) instead, change the list comprehension to range(low, high) and describe the bounds accordingly.

The function returns a list, which is convenient if the calling code needs to use the primes later. To print one prime per line instead, replace the final call with:

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

When to use a sieve instead

The helper above performs a separate divisibility check for each candidate. That makes it a clear choice for a beginner exercise or for checking a modest interval. If the task is to generate every prime from 2 up to a large limit, a Sieve of Eratosthenes may fit better: mark multiples of each prime as composite, beginning at that prime’s square. The NIST Dictionary of Algorithms and Data Structures notes that the basic sieve uses Θ(N) memory; segmented sieves reduce memory needs. There is no universal crossover point—the better method depends on the input and implementation.

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
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

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.