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 Find Sum of First n Prime Numbers

Python Programs to Find Sum of First n Prime Numbers

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). There are two ways to find the sum of the first n prime numbers between 1 and n using Python.

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 loop
    • Code Example: Calculate the sum of first 5 prime numbers.
    • Explanation
  • 2. Using Python’s Built-in filter() and itertools
    • Code Example

1. Using loop

We can use for loop to calculate the sum of the first n prime numbers by iterating through numbers from 1 to n, checking if they are prime, and summing them.

Also, see:

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

Code Example: Calculate the sum of first 5 prime numbers.

import math

def is_prime(num):
    if num <= 1:
        return False
    for i in range(2, int(math.sqrt(num)) + 1):  # optimized by the checking till √n
        if num % i == 0:
            return False
    return True

n = 4   # first 5 prime numbers
prime_sum = 0   # sum of prime numbers
prime_counter = 0 # counter of prime numbers 
num = 2  # Start from the first prime number
while prime_counter < n:
    if is_prime(num):
        print(num)
        prime_sum += num
        prime_counter += 1 
    num += 1
print(f"The sum of the first {n} prime numbers is: {prime_sum}")Code language: Python (python)

Output:

2
3
5
7
11
The sum of the first 4 prime numbers is: 28

Explanation

  • We are using a while loop to iterate over numbers starting from 2 until we get the expected number of prime numbers, which is 5 in this case.
  • In each iteration of a loop, we are doing the following operation:
    1. Checking if the number is prime using is_prime() function
    2. Printing the number if its prime
    3. Summing it with prime_sum
    4. Incrementing the prime number counter (prime_counter) by 1
    5. Increment the number by 1 to get the next number in the series, i.e., 3, 4, and so on…
    6. Iteration ends when prime_counter reaches the expected prime number count.
  • is_prime(): It is a function to find the prime number, we check divisibility num % i == 0 only up to the square root of the number, which significantly improves performance.
    • Edge case: Numbers less than or equal to 1 are immediately classified as not prime because prime numbers are greater than 1.
    • Use of math.sqrt: The math.sqrt function calculates the square root of n.
    • for Loop: The loop iterates from 2 up to and including √n, significantly reducing the number of checks needed compared to iterating through all numbers up to n-1.
    • Modulo operator (%): The modulo operator is used to check divisibility. If n % i == 0, then i is a divisor of n, indicating that the number is not prime.

2. Using Python’s Built-in filter() and itertools

Steps to find the sum of first n prime numbers using filter() and itertools:

  1. Checking for Prime Numbers

    The function is_prime() checks if a number is prime as explained earlier.
    To find the prime number, we check the divisibility num % i == 0 only up to the square root of the number, which significantly improves performance.

  2. Generating Numbers

    itertools.count(2) creates an infinite sequence starting from 2, increasing by 1 at each step.

  3. Filter Prime Numbers

    filter() applies is_prime() to each number on the generated sequence.
    Only keeps numbers for which is_prime(num) == True (i.e., prime numbers).
    Generates an infinite sequence of prime numbers.

  4. Selecting the First N Prime Numbers

    itertools.islice(primes, n) takes the first n prime numbers from the infinite sequence.

  5. Sum of prime numbers

    sum() function adds all prime numbers together.

  6. Printing the Result

    The final sum of the first n prime numbers is displayed.

Code Example

import math
import itertools

def is_prime(num):
    if num <= 1:
        return False
    for i in range(2, int(math.sqrt(num)) + 1):  # optimized by the checking till √n
        if num % i == 0:
            return False
    return True

n = 4
primes = filter(is_prime, itertools.count(2))  # Infinite generator of prime numbers
prime_sum = sum(itertools.islice(primes, n))
print(f"The sum of the first {n} prime numbers is: {prime_sum}")Code language: Python (python)

Output:

The sum of the first 4 prime numbers is: 17Code language: Python (python)

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