4/15 digit sum


#1
def digit_sum(n):
  total = 0
  for x in range(n):
    total += n + 1
  return total
    
print digit_sum(1234)

i dont understand anything


#2

Hi, how are you?

Well, the following function takes the number parameter that was inputed within the parentheses and, for each time in range(n) - range defined by parameter - it’ll add to “total” variable the parameter number (n) plus one (+1), which means, in this case, 1234+1, or, 1235.

In other words, each time in 1234 times, it’ll add to total - initially 0 - the int number 1235.

To prove it, if you multiply 1235 for 1234, it’ll return you the same output number, which is 1523990.

Code breakthrough:

> def digit_sum(n):  # define the function parameter variable
>   total = 0 # define the total
>   for x in range(n): # for each time in 1234 (parameter) times
>     total += n + 1 # increase the total by 1234 (parameter, represented by "n") plus one
>   return total # return total
>     
> print digit_sum(1234) # pass the parameter 1234 to digit_sum function

Get it?

Hope it helps


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.