BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Python Program to Find Sum of n Natural Numbers

By Chaitanya Singh | Filed Under: Python Examples

In this tutorial, we will write a simple Python program to calculate the sum of first n natural numbers.

Program to calculate sum of first n natural numbers in Python

In this program we are not using the natural number addition formula n(n+1)/2, instead we are adding the natural numbers using while loop. The user is asked to enter the value of n and then the program calculates the sum of natural numbers upto the entered value n.

# Program published on https://beginnersbook.com

# Python program to calculate the sum of n Natural Numbers

# n denotes upto which number you want to calculate the sum
# for example, if n is 5 then the sum of first 5 natural numbers
num = int(input("Enter the value of n: "))
hold = num
sum = 0

if num <= 0: 
   print("Enter a whole positive number!") 
else: 
   while num > 0:
        sum = sum + num
        num = num - 1;
    # displaying output
    print("Sum of first", hold, "natural numbers is: ", sum)

Output 1:

Enter the value of n: 6
Sum of first 6 natural numbers is:  21

Output 2:

Enter the value of n: 0
Enter a whole positive number!

Output 3:

Enter the value of n: -10
Enter a whole positive number!

Output 4:

Enter the value of n: 20
Sum of first 20 natural numbers is:  210

Python Program to Find Sum of first n Natural Numbers

Related Python Examples:

1. Python program to add digits of a number
2. Python program to add subtract multiply and divide two numbers
3. Python program to add two matrices
4. Python program to add two binary numbers

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Python Tutorial

Introduction

  • Python Tutorial
  • Python Introduction
  • Install Python
  • PyCharm IDE Installation
  • Python in PyCharm
  • Python Comments
  • Python Variables
  • Python Keywords & Identifiers
  • Python data types

Flow Control

  • Python If
  • Python if..else
  • Python if..elif..else
  • Python Nested If
  • Python for loop
  • Python while loop
  • Python break
  • Python continue
  • Python pass

Python Functions

  • Python Functions
  • Python Recursion

Python Datatypes

  • Python Numbers
  • Python List
  • Python Strings
  • Python Tuple
  • Python Dictionary
  • Python Set

Python OOPs

  • Python OOP
  • Python Class & Object
  • Python Constructors

Python Examples

  • Python Programs

Copyright © 2012 – 2022 BeginnersBook . Privacy Policy . Sitemap