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?
Advertisement
Answer
You need 2 different variables in your code — a variable where you can store the sum as you iterate through the values and add them (my_sum in my code), and another variable (i in my code) to iterate over the numbers from 0 to n.
def problem1_3(n):
my_sum = 0
i=0
#replace this pass (a do-nothing) statement with your code
while i <= n:
my_sum = my_sum + i
print(my_sum)
i+=1
return my_sum
You are using the my_sum variable in your code to both store the sum and iterate through the numbers.