Digit_sum - review the code


#1

People, the code is working as expected, but I’d like to know if there is a best way to do it, I mean I’m quite new to python and probably there is a better solution instead the for and for



def digit_sum(n):
  n = str(n)
  lista = []
  for a in n:
    lista.append(a)
  result = 0
  for x in lista:
    result += int(x) 
  return result

digit_sum(1234)



#2

best in programming is always a balance between performance, readability and maintainability

your program can certainly be a little shorter, you loop over a string to append to a list, then you loop over a the list to add to result, you can loop over the string and add to result directly.


#3

You’re correct, looks really better now:


def digit_sum(n):
  n = str(n)
  result = 0
  for x in n:
    result += int(x)
  return result

digit_sum(1234)


#4

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