Prime Number Program in Python with Examples and Variations

Advertisement

May 31, 2025 By Tessa Rodriguez

When writing programs that involve numbers, it's common to run into problems where you need to figure out if a number is prime or not. Prime numbers are simple in concept but useful in many situations, from basic exercises to more advanced programming tasks. In Python, writing a program that deals with prime numbers is a good way to work on loops, conditions, and performance. Let’s go through how to create different versions of a prime number program, each with a slightly different focus.

What Is a Prime Number?

A prime number is any integer larger than 1 that can only be divided by one and itself. So, that means when you try to divide it by anything except for those two numbers, you get a remainder. So 2, 3, 5, and 7 are prime numbers. Numbers such as 4, 6, or 9 aren't because they can be divided by other numbers without a remainder.

This idea is pretty straightforward, but it’s a useful concept in both math and programming. In coding, prime numbers show up in problem-solving, puzzles, and even in some background parts of security and encryption systems.

Step-by-Step Guide to Writing a Prime Number Program

Step 1: Write a Basic Prime Check Function

To begin, create a simple function that checks whether a number is prime. This version checks all numbers between 2 and one less than the input:

python

CopyEdit

def is_prime(n):

if n <= 1:

return False

for i in range(2, n):

if n % i == 0:

return False

return True

Here's what happens: The loop runs through all numbers starting at two and going up to, but not including, n. If any number divides n without a remainder, the function immediately returns False, meaning n isn't prime. If the loop finishes without finding a match, the number is declared prime.

Step 2: Improve the Function for Larger Numbers

The basic version works fine for smaller inputs, but it does more work than needed. If a number has a factor, that factor will always be less than or equal to its square root. So, there’s no need to go all the way up to n-1. You can stop at the square root, which reduces the number of checks:

python

CopyEdit

import math

def is_prime(n):

if n <= 1:

return False

for i in range(2, int(math.sqrt(n)) + 1):

if n % i == 0:

return False

return True

This saves time and makes the function more practical when you're checking higher numbers. The result is the same, but the loop doesn’t run as long.

Step 3: Print All Prime Numbers Within a Range

Once your is_prime function is ready, it becomes easy to apply it to a set of numbers. You can write a second function that goes through a given range and prints the prime numbers one by one:

python

CopyEdit

def primes_in_range(start, end):

for num in range(start, end + 1):

if is_prime(num):

print(num)

So if you call:

python

CopyEdit

primes_in_range(10, 30)

It will print the prime numbers between 10 and 30. This is useful when you’re exploring a dataset or writing a utility that scans numeric ranges.

Step 4: Use the Sieve of Eratosthenes for Better Performance

If you want to generate prime numbers up to a certain limit and do it quickly, especially when that limit is high, you can use the Sieve of Eratosthenes. It works by assuming all numbers are prime and then crossing off the ones that aren’t.

Here's what it looks like in Python:

python

CopyEdit

def sieve_of_eratosthenes(limit):

primes = [True] * (limit + 1)

primes[0] = primes[1] = False

for i in range(2, int(limit ** 0.5) + 1):

if primes[i]:

for j in range(i * i, limit + 1, i):

primes[j] = False

for i in range(limit + 1):

if primes[i]:

print(i)

When you run:

python

CopyEdit

sieve_of_eratosthenes(100)

It prints every prime from 0 to 100. This method is a smart choice when performance matters, especially if you're dealing with repeated calls or need to work with large numeric data.

Try Storing Prime Numbers in a List

There are times when printing isn’t enough—you may want to keep the primes in a list and use them later in your code. This is where list comprehension helps:

python

CopyEdit

primes = [x for x in range(2, 101) if is_prime(x)]

print(primes)

This one-liner checks each number from 2 to 100 and keeps the ones that pass the is_prime test. It’s useful when you need to filter or analyze primes later instead of just displaying them.

A Few Extra Variations to Consider

Once you're comfortable writing the basic prime checker and using it in different ways, there are other variations worth exploring:

Count how many primes are in a range

Instead of printing, count and return the total number of primes:

python

CopyEdit

def count_primes(start, end):

count = 0

for num in range(start, end + 1):

if is_prime(num):

count += 1

return count

Return a list of primes rather than printing.

This can be helpful in scripts where the output needs to be processed further:

python

CopyEdit

def list_primes(start, end):

return [num for num in range(start, end + 1) if is_prime(num)]

Check a list of numbers at once

Sometimes, you might have a predefined list and want to test each item:

python

CopyEdit

def check_multiple(numbers):

return {n: is_prime(n) for n in numbers}

These variations are optional, but once you know how the core logic works, it's simple to build around it.

Closing Thoughts

A prime number program in Python isn't just a beginner's exercise. It gives you a clear way to understand how loops, logic checks, and number handling work. You start with a basic version that checks one number, then expand to working with ranges, and then improve your logic for speed. As you write each version, you're building code that does more with less effort.

And while built-in libraries can do the heavy lifting for more advanced use cases, learning to write it yourself first is a solid step. It helps you reason through each part of your code and see where you can write smarter, cleaner logic. Try each version out, compare how they perform, and use what fits best for your current project.

Advertisement

Recommended Updates

Technologies

A Clear Guide to Using Python’s range() Function

Tessa Rodriguez / Jun 04, 2025

Understand how the Python range() function works, how to use its start, stop, and step values, and why the range object is efficient in loops and iterations

Technologies

Understanding the XOR Problem with Neural Networks for Beginners

Alison Perry / Jun 03, 2025

Explore the XOR Problem with Neural Networks in this clear beginner’s guide. Learn why simple models fail and how a multi-layer perceptron solves it effectively

Technologies

Why Meta's Infrastructure Focus is Key to Its AI and Metaverse Ambitions

Tessa Rodriguez / Jun 06, 2025

Meta's scalable infrastructure, custom AI chips, and global networks drive innovation in AI and immersive metaverse experiences

Technologies

6 Easy Ways to Convert a Python List to a NumPy Array

Alison Perry / May 10, 2025

Need to convert a Python list to a NumPy array? This guide breaks down six reliable methods, including np.array(), np.fromiter(), and reshape for structured data

Technologies

How Git Push and Pull Help Sync Your Work

Tessa Rodriguez / May 17, 2025

Still unsure about Git push and pull? Learn how these two commands help you sync code with others and avoid common mistakes in collaborative projects

Technologies

Top 7 Impacts of the DOJ Data Rule on Enterprises in 2025

Tessa Rodriguez / Jun 03, 2025

Learn the top 7 impacts of the DOJ data rule on enterprises in 2025, including compliance, data privacy, and legal exposure.

Technologies

How to Create Ghibli-Style Images Using ChatGPT: A Step-by-Step Guide

Tessa Rodriguez / Jun 19, 2025

Discover how to generate enchanting Ghibli-style images using ChatGPT and AI tools, regardless of your artistic abilities

Technologies

Smarter Chatbot Training With Distilabel And Argilla For Cleaner Labels

Alison Perry / Jun 11, 2025

What happens when you stop relying on majority vote and start using smarter label aggregation? See how Distilabel and Argilla helped build a chatbot with clearer, more consistent labels and faster feedback cycles

Technologies

NPC-Playground: A New Era of 3D Interaction with LLM-powered NPCs

Alison Perry / May 24, 2025

NPC-Playground is a 3D experience that lets you engage with LLM-powered NPCs in real-time conversations. See how interactive AI characters are changing virtual worlds

Technologies

OpenAI Reasoning Models: Key Features, Benefits, and Use Cases

Tessa Rodriguez / Jun 04, 2025

Explore key features, top benefits, and real-world use cases of OpenAI reasoning models that are transforming AI in 2025.

Technologies

Prime Number Program in Python with Examples and Variations

Tessa Rodriguez / May 31, 2025

Learn how to write a prime number program in Python. This guide walks through basic checks, optimized logic, the Sieve of Eratosthenes, and practical code examples

Technologies

The Role of Namespaces in Python Programming

Tessa Rodriguez / Jun 03, 2025

How Python handles names with precision using namespaces. This guide breaks down what namespaces in Python are, how they work, and how they relate to scope