I'm trying to write a program to add up the numbers from 1 to n. I've managed to get it to print the numbers several times but not to add them all. It keeps on just adding two of the numbers.
My 1st attempt is:
def problem1_3(n):
my_sum = 0
while my_sum <= n:
my_sum = my_sum + (my_sum + 1)
print()
print(my_sum)
How can I fix this problem?
For the recursive version of this question, see Recursive function to calculate sum of 1 to n?
my_sum = my_sum + (my_sum + 1)
doubles your previous value and adds1
to it. Why notmy_sum += 1
(which is equivalent tomy_sum = my_sum + 1
). Outside of that, your indentation is off and you don't show how you call the function.while my_sum <= n
This condition doesn't look correct. Did you mean to use a counter there? Consider 1 2 3 4. This will get out of the loop at 3 because the sum (1+2+3) will be larger than 4.