Skip to content

Sum of n numbers in Python using for loop | Example code

  • by

You have to take n number input from the user or provide a default value of to sum of n numbers in Python using for loop.

Example sum of n numbers in Python using for loop

Simple example code finds Sum of N Natural Numbers using While Loop, For Loop, and Functions.

Using For Loop

This program allows users to enter any integer value. After the user input number calculates the sum of natural numbers from 1 to user-specified value using For Loop.

number = int(input("Enter any Number: "))
total = 0

for value in range(1, number + 1):
    total = total + value

print("The Sum of Natural Numbers =  {1}".format(number, total))

Output:

Sum of n numbers in Python using for loop

Using While Loop

number = int(input("Enter any Number: "))
total = 0
value = 1

while value <= number:
    total = total + value
    value = value + 1

print("The Sum of Natural Numbers =  {1}".format(number, total))

Output:

Enter any Number: 4
The Sum of Natural Numbers = 10

Using Functions

def sum_n(num):
    if num == 0:
        return num
    else:
        return num * (num + 1) / 2


number = int(input("Number: "))

total = sum_n(number)
print(total)

Output:

Number: 2
3.0

Do comment if you have any doubts or suggestions on this Python sum topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.