How to print only the last result of an array of sum in python

Question:

I want to calculate the sum of the natural numbers from 1 up to an input number. I wrote this code:

number=int(input("enter a natural number"))
if number<0: 
    print("The number is not positive") 
else:   
   n=0   
   for i in range (1,number+1):
        n+=i
        print(n)

But it prints multiple numbers instead. For example, if the user puts five, the program should print 15, but I get this:

1
3
6
10
15

How can I fix the code so that only 15 appears?

Asked By: Tusa22

||

Answers:

Something like this?

number = int(input("enter a natural number"))
if number < 0:
    print("The number is not positive")
else:
    n = 0
    for i in range (1,number + 1):
        n += i
    print(n)
Answered By: Bob Smith

The answer to your question is that you are printing the n every time you change it. You are looking for the last answer when you run the code. This code should solve it.

number = int(input("enter a natural number"))
if number < 0:
    print("The num < 0")
else:
    n = 0
    l = []
    for i in range (0, number+1):   
        n+=i
        l.append(n)
    print(l[len(l)-1])
Answered By: Random

You have all the steps because your print statement is in your for loop.
Change it like this:

number = int(input("Enter a positive natural number: "))
if number < 0:
    print("The number needs to be positive")
    exit()  # Stops the program

result = 0
for i in range(1, number + 1):
    result += i

print(result)    # We print after the calculations

There’s also a mathematical alternative (see here):

number = int(input("Enter a positive natural number: "))
if number < 0:
    print("The number needs to be positive")
    exit()  # Stops the program
print(number * (number + 1) / 2)
Answered By: M3tex

As I’ve pointed out and suggested earlier in comments, you could move the print statement out of for-loop to print the final sum.

Or you could try to use generator expression to get all number’s total (sum), because we don’t care the intermediate sums.

This simple sum of all up to the number in one shot.


number=int(input("enter a natural number"))
if number < 0: 
    print("The number is not positive") 
    # exit or try again           <---------
else:
    print(sum(range(1, number + 1)))             # given 5 -> print 15 
Answered By: Daniel Hao
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.