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 a for loop.

Here’s an example of how you can calculate the sum of the first n numbers using a for loop in Python:

# Input the value of n
n = int(input("Enter a positive integer: "))

# Initialize a variable to store the sum
sum_of_numbers = 0

# Use a for loop to iterate from 1 to n
for i in range(1, n + 1):
    sum_of_numbers += i

# Print the sum
print("The sum of the first", n, "numbers is:", sum_of_numbers)

In this code:

  1. We first take an input from the user to specify the value of n.
  2. We initialize a variable sum_of_numbers to store the sum of the numbers.
  3. We use a for loop to iterate from 1 to n, adding each number to the sum_of_numbers variable.
  4. Finally, we print out the sum.

You can run this code by copying and pasting it into a Python interpreter or a script file, and it will calculate the sum of the first n positive integers.

Example sum of n numbers in Python using for loop

A simple example code finds the 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 inputs the number calculates the sum of natural numbers from 1 to the 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

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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading