Reputation: 11039
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
Reputation: 1
def run(n): total = 0 for item in range(n): total = total + item return total
print(run(11))
Upvotes: -1
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
Reputation: 1
def addNumbers(num) sum=0 for i in range(0,num+1) sum=sum+i return sum
Upvotes: 0
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
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