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?
CodePudding user response:
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
CodePudding user response:
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)
CodePudding user response:
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)
CodePudding user response:
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])