Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

I’m resolving a problem, The user input a natural number, and I have to return the final sum of the numbers from 1 to the number in the input, I solved it 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)

For example, if the user puts five, the program should return 15, but I get this:
1
3
6
10
15

How can I make to only receive the answer 15?
Thanks a lot!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

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

Continue reading