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.