IanAuld - 3 months ago 8

Python Question

I'm having trouble filling out a question on an online python tutorial. It seems really simple but for the life of me I can't figure it out. This is the problem "**write a for loop that adds all the numbers 1 to 10 and returns the sum.**" And this is the code I have been trying:

`def run():`

sum = 0

for i in range(11):

sum += i

return sum

What am I doing wrong? Thanks for any help.

Answer

You're returning within the loop, after one iteration. You need to dedent the `return`

statement so that it falls outside the loop:

```
def run():
sum_ = 0
for i in range(11):
sum_ += i
return sum_
```

Source (Stackoverflow)

Comments