To begin, you need to fix your indentation:
- def sumTo(n):
-
sum = 0
-
for i in range(1, n+1):
-
sum = sum + i
-
return sum
The code iterates over the list created by calling
range() (1, 2,....,10) and adds all the numbers to the initial value of "sum" which is 0. BTW, you should not use the name "sum" as an identifier, because the built-in function
sum() will be masked. Another way to express your function would be:
- reduce(lambda x, y: x+y, range(1, n+1), 0)
or:
- >>> import operator
-
>>> reduce(operator.add, range(1, n+1))
-
55
-
>>>