in college we got an homework. The task is to write a program that sum
the first consecutive even numbers and that the sum can not exceed 200.
The result would be:
2 + 4 + 6 + 8 + 10 + 12 + 14 + 16 + 18 + 20 + 22 + 24 + 26
Python should “answer” that:
The count of even numbers is: 13
The total is: 182
Do I take it that you need to sum the even numbers in their natural
order (2, 4, 6, … as in your example above), and not that you’re given
a mixed sequence of numbers where you need to recognise consection runs
of evens. I’ll assume the former.
I am sure that this is an easy task for most of you, but I am a
beginner so please be patient .
I am trying for a couple of days now, but I am not able to write the
So far I was able to do this:
even = 1
value = 0
while even <= 200:
even = (even + 2)
value = value +1
print ("sum of the value: ", even , "number of the value: ", value )
if even == 200:
total = int(input("How many consecutive numbers should I add up not to exceed 200: "))
if total == 5:
print("You calculated correctly: ", value - 1, “consecutive numbers is the correct answer”)
This seems a bit odd. Would not 13 be the target, given your example?
The code above does not seem to do any addition, making computing a sum
difficult. Also, you start with even=1. That is not an even number!
start with even=0 and total=0
set the loop condition to "total <= 200"
Inside the loop: bump “even” by 2 as you do. Compute a new_total = total
- even. If that exceeds 200, break out of the loop without updating
“total”. otherwise set total=new_total.
You would also want a counter of how many times you have run the loop,
in order to count the number of values you added up.
I’d get rid of the input() entirely: just run the programme, and print
the final results as in the example you gave at the top.
I would also put some print() calls inside the loop so that you can see
the values of "even’ and “total” as they go up, to check that the
correct things are happening; remove those when the behaviour is
Cameron Simpson email@example.com