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:
JavaScript
x
7
1
def problem1_3(n):
2
my_sum = 0
3
while my_sum <= n:
4
my_sum = my_sum + (my_sum + 1)
5
print()
6
print(my_sum)
7
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.
JavaScript
1
10
10
1
def problem1_3(n):
2
my_sum = 0
3
i=0
4
#replace this pass (a do-nothing) statement with your code
5
while i <= n:
6
my_sum = my_sum + i
7
print(my_sum)
8
i+=1
9
return my_sum
10
You are using the my_sum variable in your code to both store the sum and iterate through the numbers.