September 20th, 2013, 03:17 PM

Question About Fixing Simple While Loop
Hello, So I'm trying to fulfill the following requirements:
What is the sum of the even numbers from 524 through 10508, 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
Here is what I have thus far. My main issue is how to make i change through each succession of the loop. I think the problem lies within the fact that I initialized i before the loop began, and its constantly referring to its initial value of 524 and never fully changing i each time:
Code:
i = 524
while(i < 10508):
j = i + 2
result = i + j
print(result)
i = i + 2
September 20th, 2013, 05:29 PM

What is j for? Let's use your algorithm to sum the even numbers from 2 to 6, inclusively. We do this with pen and paper. We know the answer, 12, ahead of time because
2 + 6 equals 8, and there are 1½ of these.
Code:
# read from top to bottom. Only recomputed values are shown.
# i j result i<6 print expression(reason)
i = 2 # 2 i=2
while(i < 6): # True 2<6
j = i + 2 # 4 j=2+2
result = i + j # 6 result=2+4
print(result) # 6 result
i = i + 2 # 4 i=2+2
while(i < 6): # True 4<6
j = i + 2 # 6 j=4+2
result = i + j # 10 result=4+6
print(result) # 10 result
i = i + 2 # 6 i=4+2
while(i < 6): # False 6<6
j = i + 2 #
result = i + j #
print(result) #
i = i + 2 #
Trying the algorithm by hand on a small data sample is an approach. The debugger (module pdb) automates this which really helps with accuracy. I did not use pdb. This shows us that the algorithm is incorrect, the final value printed is 10 which is not 12. You already knew your program is wrong.
In this case, solving a small problem with pen and paper expedites our algorithmic discovery. You're likely to follow this:
Code:
# i result reason
# 2 start value
# 2 doh!
# 4 increment i by 2
# 6 2 + 4 is 6
# 6 add another 2 to i
# 12 6 + 6 is 12
#
# which, I'm sure you can see translates to the algorithm
i = 2 # start value
while i <= 6:
result = result + i
i = i + 2
sum(range(524, 10508+1, 2))
Hmm. This doesn't work. Can you fix it? Maybe the computer doesn't understand "doh!"
In your case the sum of the first and last terms is 11032 and there are 4993 halves of these giving an expected result of 27541388.
[code]
Code tags[/code] are essential for python code and Makefiles!
September 20th, 2013, 07:15 PM

Hint:
Somehow you have to keep adding the even numbers to a sum that starts with zero. The first number added is 524 then 526 and so on.
Real Programmers always confuse Christmas and Halloween because Oct31 == Dec25