How to Print Prime Numbers from 1 to 100 in Python

I remember the first time I had to write a script to find prime numbers. I was working on a small data security module for a fintech startup in New York.

We needed a quick way to generate prime factors for a custom hashing algorithm. It seemed like a simple task, but I quickly realized there are several ways to do it.

Some methods are great for beginners, while others are built for high-speed performance. In this tutorial, I will show you exactly how to print prime numbers from 1 to 100 using Python.

What is a Prime Number?

Before we dive into the code, let’s refresh our memory on what a prime number actually is.

A prime number is a natural number greater than 1 that cannot be formed by multiplying two smaller natural numbers.

In simpler terms, it is a number that is only divisible by 1 and itself.

For example, 2, 3, 5, and 7 are prime numbers.

However, 4 is not prime because you can make it by multiplying 2 x 2.

Method 1: Use a Simple Nested For Loop

This is the easiest way to get the job done, and it’s how I usually explain the logic to junior developers.

We use two loops: an outer loop to go through numbers 1 to 100, and an inner loop to check if the current number has any divisors.

Here is the full code:

# Python program to print prime numbers from 1 to 100
# This method uses a simple nested loop approach

print("Prime numbers between 1 and 100 are:")

for num in range(1, 101):
    # Prime numbers must be greater than 1
    if num > 1:
        for i in range(2, num):
            if (num % i) == 0:
                # If a divisor is found, it's not prime
                break
        else:
            # If the loop finished without finding a divisor
            print(num, end=" ")

You can see the output in the screenshot below.

python program to print prime numbers from 1 to 100

In this script, the else block belongs to the for loop, not the if statement. This is a neat Python feature that only executes if the loop finishes naturally without hitting a break.

Method 2: Optimize with the Square Root (The Pro Way)

When I’m writing production-level code, I always look for ways to save processing power. You don’t actually need to check every number up to num to see if it’s prime.

Mathematically, you only need to check up to the square root of the number. If no divisor is found by that point, there won’t be one later on.

Here is the optimized code:

import math

def is_prime_optimized(n):
    if n <= 1:
        return False
    # Only check up to the square root of n
    for i in range(2, int(math.sqrt(n)) + 1):
        if n % i == 0:
            return False
    return True

print("Optimized Prime Numbers (1-100):")
for num in range(1, 101):
    if is_prime_optimized(num):
        print(num, end=" ")

You can see the output in the screenshot below.

print prime numbers from 1 to 100

This method is much faster because it does fewer calculations per number. I find this particularly useful when the range increases from 100 to 100,000.

Method 3: Use List Comprehension (The One-Liner)

Sometimes you want your code to be concise, especially during a quick code review or in a Jupyter Notebook.

Python allows you to handle the prime number logic in a single line using list comprehension.

While it’s a bit harder to read for beginners, it’s very “Pythonic.”

# Prime numbers from 1 to 100 in one line
primes = [x for x in range(2, 101) if all(x % y != 0 for y in range(2, int(x**0.5) + 1))]

print("Primes using List Comprehension:")
print(primes)

You can see the output in the screenshot below.

prime numbers 1 to 100

I wouldn’t use this for complex logic, but for a simple range like 1 to 100, it’s a clean solution. The all() function checks if every condition in the generator is true.

Method 4: The Sieve of Eratosthenes (The Fastest Algorithm)

If you are dealing with large datasets, common in data science roles across the US, you need the Sieve of Eratosthenes.

This is an ancient algorithm that “sieves” out the non-prime numbers by marking multiples.

It is significantly faster than checking each number individually.

def sieve_of_eratosthenes(limit):
    prime_flags = [True] * (limit + 1)
    prime_flags[0] = prime_flags[1] = False
    
    for p in range(2, int(limit**0.5) + 1):
        if prime_flags[p]:
            # Mark all multiples of p as False
            for i in range(p * p, limit + 1, p):
                prime_flags[i] = False
                
    return [num for num, is_p in enumerate(prime_flags) if is_p]

print("Primes using Sieve of Eratosthenes:")
print(sieve_of_eratosthenes(100))

This approach is my go-to when performance is the top priority. It avoids the heavy use of the modulo operator %, which can be slow in large loops.

Real-World Application: Why Prime Numbers Matter

In my experience, prime numbers aren’t just for math class. In the US tech industry, they are the backbone of modern cybersecurity.

RSA encryption, which secures your online bank transfers and Amazon purchases, relies on the difficulty of factoring large prime numbers.

I’ve also used primes in load-balancing algorithms to distribute traffic evenly across servers.

When you use a prime number for a hash table size, it helps reduce “collisions,” making your data retrieval much faster.

Common Mistakes to Avoid

When I review code from junior developers, I often see the same few errors:

  • Forgetting 0 and 1: Remember that prime numbers start at 2. 0 and 1 are never prime.
  • Checking Even Numbers: Once you check 2, you don’t need to check any other even numbers.
  • Missing the Break: If you find one divisor, stop immediately. Don’t keep checking.

I hope this guide helps you understand the different ways to handle primes in Python.

Whether you need a quick script or a high-performance algorithm, these methods have you covered.

You may read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.