简体   繁体   中英

Sum of odd numbers in a range

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)

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) ) )

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM