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!
>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)