Write a Python algorithm that asks the user to enter an integer n and display the value of the sum = 1 + 2 + … + n


# ask user to enter 
n = int(input("Enter a positive integer: "))

# initializing the sum
sum = 0

# browsing through all integers from 1 to n
for i in range(1, n+1):
    sum += i

print("The sum of the first", n, "positive integers is: ", sum)

In this program:

  1. we first ask the user: to enter a positive integer n using the input() function and convert it to an integer using the int() function.
  2. We then initialize a variable sum to 0: which will be used to keep track of the sum of the integers.
  3. We use a for loop: to iterate over the integers from 1 to n using the range() function.
  4. For each integer i: we add it to the current value of sum.
  5. Finally, we use the print() function: to display the result of the sum.


Younes Derfoufi

One thought on “Solution Exercise 8: algorithm python to compute the sum of first n integers”

Leave a Reply