kylieCatt
kylieCatt

Reputation: 11039

Adding Numbers in a Range with for() Loop

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.

Upvotes: 1

Views: 108270

Answers (5)

KennedyKiria
KennedyKiria

Reputation: 1

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

print(run(11))

Upvotes: -1

Manh Duc Tran
Manh Duc Tran

Reputation: 11

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)

Upvotes: 1

Nirmal Sudharman
Nirmal Sudharman

Reputation: 1

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

Upvotes: 0

Platinum Azure
Platinum Azure

Reputation: 46183

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_

Upvotes: 10

Senthil Kumaran
Senthil Kumaran

Reputation: 56833

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

Upvotes: 0

Related Questions