Sum of Even Numbers help!

Hello all, this is my first post so I apologize for any misconduct.

I am working through a problem where I need to write a script to find the sum of even numbers within a range, 0 to 100 to be exact.

this is my code:

result = 0

for i in range (0,100):
if i%2==0:
result =+ i
print(result)

when I run this it returns a collection of 50 numbers instead of a single sum. what am I missing to add all the even numbers together so that I can print the total?

First off, you don’t “return” anything. It’s important to understand that printing some text and returning a value are completely unrelated tasks:

Let’s think about the logic. If we want to print only once, then the call to print should be outside the loop, right? So, fix the indentation of the code, so that it’s outside the loop.

Aside from that, =+ isn’t a thing. result =+ i means result = +i, which is essentially the same as result = i. You want += instead.

As we’ve learned here, indentation is important in Python. Therefore, please make sure to format the code correctly when posting here, so that we can see it indented as you actually have it. Please read the pinned thread to understand how.

1 Like

I would guess your print is within the loop so it is printing the sum after every iteration.

Alternative approach:

sum(filter(lambda x: not x % 2, range(100)))

sum(range(0, 100, 2))

1 Like

If you need to add all even numbers between 2k_1 and 2k_2, both included, with k_2\geq k_1, then you can compute the sum as

\frac{(2k_1+2k_2)(k_2-k_1+1)}{2}=(k_1+k_2)(k_2-k_1+1)

For example, the sum 2+4+6+\ldots+98=2\cdot 1+2\cdot 2+2\cdot 3+\ldots +2\cdot 49 is (1+49)(49-1+1)=50\cdot 49=2450

>>> sum(range(0,100,2))
2450

Regarding your

It sounds like you might have your print statement inside the IF. Check if the indentation that you have is like this

result = 0

for i in range (0,100):
    if i%2==0:
        result =+ i
        print(result)

The print statement should be outside of the IF and outside of the FOR, like this

result = 0

for i in range (0,100):
    if i%2==0:
        result =+ i
print(result)

such that it corresponds to the intention of printing once after all the adding has been done, instead of printing every time an even number is found.

1 Like