Write a function s sumn n to calculate the sum from 0 to n python

In the program below, we've used an if...else statement in combination with a while loop to calculate the sum of natural numbers up to num.

Source Code

# Sum of natural numbers up to num

num = 16

if num < 0:
   print("Enter a positive number")
else:
   sum = 0
   # use while loop to iterate until zero
   while(num > 0):
       sum += num
       num -= 1
   print("The sum is", sum)

Output

The sum is 136

Note: To test the program for a different number, change the value of num.

Initially, the sum is initialized to 0. And, the number is stored in variable num.

Then, we used the while loop to iterate until num becomes zero. In each iteration of the loop, we have added the num to sum and the value of num is decreased by 1.


We could have solved the above problem without using a loop by using the following formula.

n*(n+1)/2

For example, if n = 16, the sum would be (16*17)/2 = 136.

Your turn: Modify the above program to find the sum of natural numbers using the formula below.

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

Write a function s sumn n to calculate the sum from 0 to n python

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

In this python tutorial, you will learn about Python program to find sum of n numbers and also we will check:

  • Python program to find sum of 3 numbers
  • Python program to find sum of n numbers using for loop
  • Python program to find sum of n numbers using a function
  • Python program to find sum of n numbers using while loop
  • python program to find sum of n numbers using recursion
  • Python program to find sum of n even numbers
  • Python program to find sum of n odd numbers
  • Python program to find sum of n prime numbers
  • Python program to find sum of first n numbers
  • Python program to find sum of first n even numbers
  • Python program to find sum of numbers in a list
  • Python program to find sum of numbers in a string
  • Python program to find sum of numbers in a file

Now, we can see how to find the sum of 3 numbers in python.

In this example, I have taken three inputs. The int data type is used and the “+” operator is used to find the sum of the three numbers.

Example:

number1 = input('Enter first number: ')
number2 = input('Enter second number: ')
number3 = input('Enter third number')
sum = int(number1) + int(number2) + int(number3)
print(sum)

We can see the sum of three inputs is 16 as the output. You can refer to the below screenshot for the output.

Write a function s sumn n to calculate the sum from 0 to n python
Python program to find the sum of 3 numbers

This is how to find sum of 3 numbers in Python.

You may like to read, How to print factorial of a number in Python and How to calculate simple interest in Python.

Python program to find sum of n numbers using for loop

Here, we can how to find the sum of n numbers using for loop in python.

  • In this example, I have taken an input. The int data type is used to sum only the integers.
  • Here, we can take an initial value sum = 0. The for loop is used for iteration number + 1 is used to increase the number up to the given input.
  • The sum = sum + value is used to find the sum.
  • To get the output, I have used print(sum).

Example:

number = int(input("Enter the Number: "))
sum = 0
for value in range(1, number + 1):
    sum = sum + value
print(sum)
 

We can see the sum of number till 10 is 55 as the output. You can refer to the below screenshot for the output.

Write a function s sumn n to calculate the sum from 0 to n python
Python program to find the sum of n numbers using for loop

This is how to find sum of n numbers using for loop in Python.

You may like Python For Loop with Examples

Python program to find sum of n numbers using a function

Here, we can how to find the sum of n numbers using a function in python.

  • In this example, I have taken an input. The function is defined as def sum(n).
  • The if condition is used if the input is less than 1 it returns n itself, if the number is greater than one the else condition is executed and then n is added to sum(n-1).
  • The print(“The sum is: “, sum(num)) is used to get the output.

Example:

num = int(input("Enter a number: "))
def sum(n):
    if n <= 1:
        return n
    else:
        return n + sum(n-1)
print("The sum is: ", sum(num))

As the input is 6. We can see the sum of numbers is 21 as the output. The below screenshot shows the output.

Write a function s sumn n to calculate the sum from 0 to n python
Python program to find the sum of n numbers using a function

This is how to find sum of n numbers using a function in Python.

You may like, Function in Python.

Python program to find sum of n numbers using while loop

Now, we can see how to find sum of n numbers using while loop in python.

  • In this example, I have taken an input. The if condition is used if the input is less than 0 then print(“Enter a positive number”) is displayed.
  • If the number is greater than 0, else condition is executed if sum =0 the while condition is executed as a number is greater than 0.
  • The sum += input is used to increment a value and input -= 1 is used to decrement a value.

Example:

input = int(input("Enter a number: "))  
if input < 0:  
   print("Enter a positive number")  
else:  
   sum = 0  
   while(input > 0):  
       sum += input  
       input -= 1  
   print("The result is",sum)  

The below screenshot shows the sum of numbers as the output.

Write a function s sumn n to calculate the sum from 0 to n python
python program to find sum of n numbers using while loop

The above code, we can use to find sum of n numbers using while loop in Python.

Check out While loop in Python.

Python program to find sum of n numbers using recursion

Here, we can see how to find sum of n numbers using recursion in python.

  • Python Recursion means calling the function itself.
  • In this example, I have defined a function as def recursion(n).
  • The if condition is used, if the number is less than 9 it should return the number itself.
  • If the number is greater than or equal to 9 it returns n + recursion(n – 1).
  • The print(recursion(n)) is used to get the output.

Example:

def  recursion(n): 
	if n <= 1: 
		return n 
	return n +  recursion(n - 1) 
n = 9
print(recursion(n)) 

The below screenshot show the sum of numbers upto 9 as the output.

Write a function s sumn n to calculate the sum from 0 to n python
Python program to find sum of n numbers using recursion

The above code we can use to find sum of n numbers using recursion in Python.

Python program to find sum of n even numbers

Now, we can see how to find sum of n even numbers in python

  • In this example, I have taken an input. The initial value is set as total = 0
  • The for loop is used for iteration. I have used the range function().
  • The if condition is used as number % 2 ==0 to get the even numbers.
  • The print(number) is used to get the even numbers
  • The total = total + number is used to find the sum of even numbers.

Example:

Even = int(input("Enter the input"))
total = 0
for number in range(1, Even+1):
    if(number % 2 == 0):
        print(number)
        total = total + number
print("The sum of even numbers", total)

The sum of even numbers is the output. You can refer to the below screenshot for the output.

Write a function s sumn n to calculate the sum from 0 to n python
python program to find sum of n even numbers

This is how to find sum of n even numbers in Python.

Python program to find sum of n odd numbers

Here, we can see how to find the sum of n odd numbers in python

  • In this example, I have taken an input. The initial value is set as total = 0.
  • The for loop is used for iteration. I have used the range function.
  • The if condition is used as number % 2! =0 to get the odd numbers.
  • The print(number) is used to get the odd numbers.
  • The total = total + number is used to find the sum of odd numbers.

Example:

Odd = int(input("Enter the input"))
total = 0
for number in range(1, Odd+1):
    if(number % 2!=0):
        print(number)
        total = total + number
print("The sum of odd numbers", total)

We can see the sum of odd numbers as the output. You can refer to the below screenshot for the output.

Write a function s sumn n to calculate the sum from 0 to n python
Python program to find the sum of n odd numbers

This code, we can use to find sum of n odd numbers in Python.

Python program to find sum of n prime numbers

Here, we can see how to find the sum of n prime numbers in python.

  • In this example, I have taken an input. The initial value is set as sum = 0.
  • The for loop is used for iteration. The range function is used to specify the range limit between the numbers as (2, input + 1).
  • The break loop is used to terminate the current loop and resumes the execution at the next statement.
  • If condition is used to check the number is prime or not. The if i is not num the increment operator is used.
  • To get the output, I have used print(“The sum of prime numbers upto”, input, “:”, sum).

Example:

input = int(input("Enter a prime number"))
sum = 0
for num in range(2, input + 1):
    i = 2
    for i in range(2, num):
        if (int(num % i) == 0):
            i = num
            break;
    if i is not num:
        sum += num
print("The sum of prime numbers upto", input, ":", sum)

We can see the sum of prime numbers with the given range as the output. You can refer to the below screenshot for the output.

Write a function s sumn n to calculate the sum from 0 to n python
Python program to find the sum of n prime numbers

This is how to find sum of n prime numbers in Python.

You may like to read, Check if a number is a prime Python.

Python program to find sum of first n numbers

Here, we can see how to find the sum of first n number in python.

  • In this example, I have taken input and the initial value is set to 0 as sum = 0.
  • The for loop is used for iteration the range function is used to find the sum between the given range of input.
  • The input + 1 is used for increment, to add the numbers I have used sum = sum + num.
  • I have used print(“Result of first n numbers “,sum) to get the output.

Example:

input = int(input("Enter number"))
sum = 0
for num in range(input + 1):
    sum = sum + num
print("Result of first n numbers ",sum)

The below screenshot shows the sum of first n numbers as the output.

Write a function s sumn n to calculate the sum from 0 to n python
Python program to find the sum of first n numbers

The above code we can use to find sum of first n numbers in Python.

Python program to find sum of first n even numbers

Now, we can see how to find the sum of first n even numbers in python.

  • In this example, I have taken an input the initial value is set to 0 as sum = 0.
  • The range function is used to find the sum between the range of the numbers given by the user as the input.
  • The if((i % 2) == 0) is used to check the given number is even number.
  • If the number is even then sum = sum + i is used to add the numbers.

Example:

input = int(input("Enter the input "))
sum = 0
for i in range(1, input + 1):
    if((i % 2) == 0):
        sum = sum + i
print("Sum of even numbers from 1 to", input, "is :", sum)

The below screenshot shows the sum of even numbers as the output.

Write a function s sumn n to calculate the sum from 0 to n python
Python program to find the sum of first n even numbers

The above code we can use to find sum of first n even numbers in Python.

Python program to find sum of numbers in a list

Now, we can see how to find the sum of numbers in a list in python

  • In this example, I have taken an initial value as 0.
  • The list is assigned as list = [1, 4, 2, 3, 7]. The for loop is used for iteration
  • The sum = sum + list[ele] is used to find the sum of numbers from the list.
  • I have used print(“Sum of elements in list: “, sum) to get the output.

Example:

sum = 0
list = [1, 4, 2, 3, 7] 
for ele in range(0, len(list)):
	sum = sum + list[ele]
print("Sum of elements in list: ", sum)

We can the sum of numbers from the list is 17 as the output. You can refer to the below screenshot for the output.

Write a function s sumn n to calculate the sum from 0 to n python
Python program to find the sum of numbers in a list

This is the Python program to find sum of numbers in a list.

Python program to find sum of numbers in a string

Now, we can see how to find the sum of numbers in the string in python

  • In this example, I have taken input The initial value is set to 0 as sum = 0.
  • The for loop is used for iteration the if condition is used and the .isnumeric() method is used to take input as alphanumeric numbers.
  • The sum+int(i), here int is used only to add the numbers from the alphanumeric string.
  • I have used print(sum) to get the output.

Example:

string = input("Enter the String: ")
sum = 0
for i in string:
    if( i.isnumeric() ):
        sum = sum+int(i)
print(sum)

In the below screenshot we can see the input as 1a2b34, the sum of numbers is 10 as the output.

Write a function s sumn n to calculate the sum from 0 to n python
Python program to find the sum of numbers in a string

This is the code to find sum of numbers in a string in Python.

Python program to find sum of numbers in a file

Now, we can see how to find the sum of numbers in a file in python

  • In this example, I have opened a file as number which contains numbers in it. The number.txt is the name of the file.
  • The file.readlines() is used to read the numbers from the file.
  • The for loop is used for iteration, The .isdidgits() is used to check the character from the file is a digit.
  • The int(i) is used to add only if the digit is present in the file.
  • I have used print(“The sum is:”, sum) to get the output.

Example:

file = open('number.txt', 'r') 
content = file.readlines() 
sum = 0
for line in content: 
	for i in line: 
		if i.isdigit() == True: 
			sum += int(i) 
print("The sum is:", sum) 

The below screenshot shows the content of the file.

Write a function s sumn n to calculate the sum from 0 to n python
find sum of numbers in a file in python

The numbers from the file is added and the output is 22. You can refer to the below screenshot for the output.

Write a function s sumn n to calculate the sum from 0 to n python
Python program to find the sum of numbers in a file

The above code, we can use to find sum of numbers in a file in Python.

You may like the following python tutorials:

  • Python program to print prime numbers
  • Python format number with commas
  • Python generate random number and string
  • Python square a number
  • Python program to print element in an array

In this Python tutorial, we have learned about the Python program to find the sum of numbers. Also, we covered these below topics:

  • Python program to find the sum of 3 numbers
  • Python program to find the sum of n numbers using for loop
  • Python program to find the sum of n numbers using a function
  • Python program to find the sum of n numbers using while loop
  • python program to find the sum of n numbers using recursion
  • Python program to find the sum of n even numbers
  • Python program to find the sum of n odd numbers
  • Python program to find the sum of n prime numbers
  • Python program to find the sum of first n numbers
  • Python program to find the sum of first n even numbers
  • Python program to find the sum of numbers in a list
  • Python program to find the sum of numbers in a string
  • Python program to find the sum of numbers in a file

Write a function s sumn n to calculate the sum from 0 to n python

Python is one of the most popular languages in the United States of America. I have been working with Python for a long time and I have expertise in working with various libraries on Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… I have experience in working with various clients in countries like United States, Canada, United Kingdom, Australia, New Zealand, etc. Check out my profile.

How do you find the sum of n numbers in Python?

Sum and average using a mathematical formula.
The sum of the first n natural number = n * (n+1) / 2..
the average of first n natural number = (n * (n+1) / 2) / n..

How do you write a sum function in Python?

The sum() function is used to get the sum of all items in an iterable..
Version: ... .
Syntax: sum(iterable[, start]).
Parameter: ... .
Return value: ... .
Example: Python sum() num = [3.5, 5, 2, -5] # start parameter is not provided numSum = sum(num) print(numSum) # start = 15 numSum = sum(num, 15) print(numSum) ... .
Pictorial Presentation:.

How do you write the sum of n natural numbers in Python?

See this example:.
num = int(input("Enter a number: ")).
if num < 0:.
print("Enter a positive number").
sum = 0..
# use while loop to iterate un till zero..
while(num > 0):.
sum += num..

What is sum () sum () in Python?

Python sum() Function The sum() function returns a number, the sum of all items in an iterable.