syntax question

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • mathkid182
    New Member
    • Apr 2013
    • 1

    syntax question

    Code:
    def sumTo(n):
        sum = 0
         for i in range(1, n+1):
           sum = sum + i
    return sum
    hi with the code above can someone please walk me through what is actually happening with n is equal to say 10 and the output is 55?

    many thanks!
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    To begin, you need to fix your indentation:
    Code:
    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:
    Code:
    reduce(lambda x, y: x+y, range(1, n+1), 0)
    or:
    Code:
    >>> import operator
    >>> reduce(operator.add, range(1, n+1))
    55
    >>>

    Comment

    Working...