1

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.

0

5 Answers 5

10

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_
Sign up to request clarification or add additional context in comments.

2 Comments

That did it. Thanks a lot. Just started messing around with Python today so I'm still getting used to the syntax of everything. Thanks again!
don't use sum as a variable name, that way you can;t use the sum() `built-in.
1

if anyone want to know how to add 0 + 1 count until 100. There is it!

  x = 0
    while x<100:
        x += 1
        print(x)

Comments

0

You are returning the sum from within the for loop. Indent it outside. Keep it at the same level of indentation as for.

3 Comments

Nothing new =) Platinum Azure is very fast.
It's honestly just luck. For every answer I get first, I lose out on about ten.
@PlatinumAzure it is a fun game tough. :)
0

You need to dedent the return statement so that it falls outside the loop:

def addNumbers(num)
    sum=0
    for i in range(0,num+1)
        sum=sum+i
    return sum

1 Comment

Please edit you answer first, check this: stackoverflow.com/help/formatting
-1

def run(n): total = 0 for item in range(n): total = total + item return total

print(run(11))

1 Comment

This is a copy/paste of the code in the 8 year old answer of Platinum Azure. Please don't copy (parts of) other people's answers and pass them off as your own. And when answering older question, please make sure that you provide either a different solution or at least a significantly better explanation than current answers.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.