DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober 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 Now×
Skip to content
World desk3 min

Python Program to Print Prime Numbers: 1 to 100, Up to N, and First N

Use trial division to print primes from 1 to 100 or up to an inclusive limit, and a count-based loop to generate the first N primes.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To print primes from 1 through 100, test each candidate starting at 2 and include 100 by using range(2, 101). For a limit named N, use range(2, N + 1). To find the first N primes, use a count-based loop instead: keep testing candidates until you have collected N primes.

What counts as a prime number?

A prime is an integer greater than 1 whose only positive divisors are 1 and itself. That means 1 is not prime, while 2 is prime and is the first value a prime-number search should test. The Python tutorial’s prime-search example uses this trial-division approach.

As an Amazon Associate I earn from qualifying purchases.

Python program to print primes from 1 to 100

This function returns True only when its argument is prime. It checks possible divisors up to the square root of the number, using math.isqrt to get an integer square root.

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

def is_prime(number):
    if number < 2:
        return False
    for divisor in range(2, isqrt(number) + 1):
        if number % divisor == 0:
            return False
    return True

for candidate in range(2, 101):
    if is_prime(candidate):
        print(candidate)

The output is one prime per line, from 2 through 97. The candidate range starts at 2 so it does not test 1. Python’s range(start, stop) excludes the stop value, so range(2, 101) includes 100. The official range documentation describes this endpoint behavior.

Print every prime from 1 through a limit N

When you want primes no greater than a particular upper bound, replace the fixed endpoint with a variable and add 1 so that the endpoint is included:

upper = 100

for candidate in range(2, upper + 1):
    if is_prime(candidate):
        print(candidate)

For example, setting upper = 20 prints primes through 19, because 20 is not prime. If the upper bound is less than 2, the loop has no candidates and prints nothing. If you accept a limit from user input, convert it to an integer before using it as a range endpoint.

Print the first N prime numbers

“First N primes” means a requested number of results, not primes whose values are at most N. Use a counter in the form of a list and continue testing increasing candidates until the list contains the requested number:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
count = 10
primes = []
candidate = 2

while len(primes) < count:
    if is_prime(candidate):
        primes.append(candidate)
    candidate += 1

print(primes)

With count = 10, the program prints the first ten primes, ending at 29. A count of zero or less produces an empty list immediately. If you read count from input, convert it to an integer and decide how your program should handle negative values.

Why checking divisors only to the square root works

If a number is composite, it can be written as a product of two factors. They cannot both be greater than its square root, because their product would then be greater than the number. So at least one factor is no greater than the square root; if no divisor is found by that point, the candidate is prime. The trial-division and sieve chapter in Cracking Codes with Python explains this stopping point.

The expression number % divisor == 0 checks whether division leaves no remainder. The Python reference for arithmetic operations documents % as the remainder operator. Starting divisor checks at 2 avoids testing 1, which divides every integer.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Trial division or the Sieve of Eratosthenes?

Approach Best suited to How it works Memory and complexity
Trial division Small bounds, a few candidates, or learning how primality checks work Test each candidate against possible divisors through its square root. Compact implementation; the example checks candidates one at a time without storing a full range of results.
Sieve of Eratosthenes Generating all primes up to a fixed bound, especially as the bound grows Mark multiples of each prime as composite; the unmarked values are prime. Stores marking information up to the bound. The cited chapter describes it as much faster for finding all primes in a range, but gives no hardware-specific timing or speed ratio.

For a beginner’s first program or a modest bound, trial division is easy to read and reuse. For a large fixed range where you need every prime, a sieve avoids independently checking each candidate against possible divisors.

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

Common mistakes to avoid

  • Starting at 1: 1 is not prime, so begin candidate searches at 2.
  • Forgetting the exclusive stop: use N + 1 when the requested limit N should be included.
  • Confusing a limit with a count: primes up to 100 and the first 100 primes are different results; the latter needs a count-based loop.
  • Testing 1 as a divisor: every integer is divisible by 1, so that check cannot establish primality.

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 *

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.

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
Outdated Drivers Are Slowing You DownFree scan - exact matches
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.