3

What is the sum of the odd numbers from 1523 through 10503, inclusive? Hint: write a while loop to accumulate the sum and print it. Then copy and paste that sum. For maximum learning, do it with a for loop as well, using range.

What I tried. I need to print the sum as a total. My answer gives me the individual runs.

i=1523
while i<10503:
    sum=0
    i=i+2
    sum=sum+i
    print(sum)


for i in range(1523,10503):
    print(i+2)
Georgy
  • 12,464
  • 7
  • 65
  • 73
Evan Dissanayake
  • 33
  • 1
  • 2
  • 6

2 Answers2

9

You assignment says "inclusive", hence you should include 10503 into the sum:

i = 1523
total = 0
while i <= 10503:
    total += i
    i += 2
print (total)

total = 0
for i in range (1523, 10504, 2):
    total += i
print (total)

Also avoid using builtin names, like sum. Hence I changed it to total.

On a side note: Although your assignment asks explicitely for control statements, you (or at least I) would implement it as:

print (sum (range (1523, 10504, 2) ) )
Hyperboreus
  • 31,997
  • 9
  • 47
  • 87
  • Amazing comprehensive answer for how concise it is. Of course there's no `reduce` over a mutating `__iadd__` method on a wrapper around a `ctypes.c_int`… :) – abarnert Aug 02 '13 at 00:28
0

As Troy said, put the sum=0 before the loop. Then put print(sum) after the while loop.

Magnilex
  • 11,584
  • 9
  • 62
  • 84
TheDoctor
  • 1,450
  • 2
  • 17
  • 28