PYnative

Python Programming

  • Learn Python
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Exercises
    • Python Exercises
    • C Programming Exercises
    • C++ Exercises
  • Quizzes
  • Code Editor
    • Online Python Code Editor
    • Online C Compiler
    • Online C++ Compiler
Home » Python » Programs and Examples » Python Programs to Print Alternate Prime Numbers till N

Python Programs to Print Alternate Prime Numbers till N

Updated on: April 8, 2025 | Leave a Comment

A Prime Number is a number that can only be divided by itself and 1 without remainders (e.g., 2, 3, 5, 7, 11).

This article covers a Python programs that prints alternate prime numbers up to a given number n. We have discussed the various methods, each with an example and detailed explanation.

To solve this problem you need to know how to use the below concepts.

  • for loop, range() function and while loop
  • if-else condition
  • Math module

Table of contents

  • 1. Using a List to Store All Prime Numbers
  • 2. Using a Counter for Alternate Primes
  • 3. Using Generators for Efficient Prime Generation

1. Using a List to Store All Prime Numbers

This method in Python checks if the number is prime, stores it in a list, and then prints alternate elements from that list.

Also, See:

  • Python Programs to Check if Number is Prime Number
  • Python Programs to Find Prime Numbers within a Range

Code Example

# Function to check if a number is prime
def is_prime(num):
    if num < 2:
        return False
    for i in range(2, int(num ** 0.5) + 1):
        if num % i == 0:
            return False
    return True

# Set N
n = 20
primes = []  # List to store all prime numbers
for num in range(2, n + 1):
    if is_prime(num):
        primes.append(num)

# Printing all prime numbers
print(f'All prime numbers from 1 to {n}: {primes}')

# Printing alternate prime numbers from the list
print(f'Alternate prime numbers from 1 to {n}:')

for i in range(0, len(primes), 2):  # Step by 2 to get alternate primes
    print(primes[i])Code language: Python (python)

Output:

All prime numbers from 1 to 20: [2, 3, 5, 7, 11, 13, 17, 19]
Alternate prime numbers from 1 to 20:
2
5
11
17

Explanation

1. is_prime(num) function:

  • This function checks if a number is prime or not.
  • To check if a number is prime, we need to see if it has any divisors other than 1 and itself.
  • Instead of checking all numbers up to num, we only check up to its square root (√num).
  • If a number is not prime, it must have at least one factor smaller than or equal to its square root.
  • The expression num ** 0.5 is used to calculate the square root of num in Python (√n ​=n^0.5).

For example:

Checking is_prime(15)
Is 15 less than 2? → No.
Find square root of 15 → √15 ≈ 3.8, so we check 2, 3.
Check if 15 is divisible by 2 → 15 % 2 != 0 (not divisible).
Check if 15 is divisible by 3 → 15 % 3 == 0 → so 15 is not a prime number

2. Use for loop to check all numbers from 2 to n

  • If is_prime(num) is True, add it to the primes list.
  • Now use the range() function to print numbers. range(0, len(primes), 2) is used to print alternate prime numbers from primes list using steps through the list in increments of 2 (i.e., it skips one prime number after printing one).

2. Using a Counter for Alternate Primes

This method in Python avoids storing all primes in a list and directly prints alternate primes by using a counter to track every second prime number.

Code Example

# Function to check if a number is prime
def is_prime(num):
    if num < 2:
        return False
    for i in range(2, int(num ** 0.5) + 1):
        if num % i == 0:
            return False
    return True

n = 20
counter = 0  # Counter to track alternate primes
for num in range(2, n + 1):
    if is_prime(num):
        if counter % 2 == 0:  # Print only alternate primes
            print(num, end=' ')
        counter += 1  # Increment counter for every prime number found


# Output:
# 2 5 11 17Code language: Python (python)

Explanation

  • n = 20, meaning we want to find and print prime numbers up to 20.
  • We introduce a counter variable that increments every time a prime number is found.
  • Only when the counter is even the prime number is printed (if count % 2 == 0). This ensures that every second prime number is skipped (i.e., we print alternate primes).
  • The counter is incremented by 1 after each prime.
  • The is_prime() function remains the same as the previous method for checking if the number is prime.

3. Using Generators for Efficient Prime Generation

This method in Python uses a generator to yield prime numbers and prints alternate primes using the generator.

A generator in Python is a special type of iterator used to produce a sequence of values lazily, one at a time, as needed. Unlike regular functions that return a single value and exit, generators use the yield keyword to pause and resume execution, allowing them to generate values on demand without storing the entire sequence in memory. This makes them memory-efficient for handling large datasets or infinite sequences.

Code Example

# Function to check if a number is prime
def is_prime(num):
    if num < 2:
        return False
    for i in range(2, int(num ** 0.5) + 1):
        if num % i == 0:
            return False
    return True

# Using a generator to yield prime numbers
def prime_generator(n):
    for num in range(2, n + 1):
        if is_prime(num):
            yield num  # Yield prime number

n = 20
counter = 0
for prime in prime_generator(n):
    if counter % 2 == 0:  # Print alternate primes
        print(prime, end=' ')
    counter += 1
    
# Output:
# 2 5 11 17Code language: Python (python)

Explanation

prime_generator(n) function:

  • It takes an integer n as input.
  • A for loop iterates through each number from 2 to n.
  • For each number, it calls the is_prime(num) function to check if it is prime.
  • If the number is prime, the yield statement produces the prime number without exiting the function. This makes the function a generator, which allows us to iterate over the prime numbers one at a time.
  • For printing the alternate prime number, we are maintaining the counter variable, the logic is the same as discussed previously.

Filed Under: Programs and Examples, Python, Python Basics

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Programs and Examples Python Python Basics

All Coding Exercises:

C Exercises
C++ Exercises
Python Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your entire code </pre>

In: Programs and Examples Python Python Basics
TweetF  sharein  shareP  Pin

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

  Python Tutorials

  • Get Started with Python
  • Python Statements
  • Python Comments
  • Python Keywords
  • Python Variables
  • Python Operators
  • Python Data Types
  • Python Casting
  • Python Control Flow statements
  • Python For Loop
  • Python While Loop
  • Python Break and Continue
  • Python Nested Loops
  • Python Input and Output
  • Python range function
  • Check user input is String or Number
  • Accept List as a input from user
  • Python Numbers
  • Python Lists
  • Python Tuples
  • Python Sets
  • Python Dictionaries
  • Python Functions
  • Python Modules
  • Python isinstance()
  • Python OOP
  • Python Inheritance
  • Python Exceptions
  • Python Exercise for Beginners
  • Python Quiz for Beginners

All Python Topics

  • Python Basics
  • Python Exercises
  • Python Quizzes
  • Python File Handling
  • Python Date and Time
  • Python OOP
  • Python Random
  • Python Regex
  • Python Pandas
  • Python Databases
  • Python MySQL
  • Python PostgreSQL
  • Python SQLite
  • Python JSON

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2026 pynative.com