Given a natural number N. Calculate the sum of its numbers. Where I nakosyachil? PS do not need to offer me a solution in cycles. I am interested in the logic of working out my code. Why my code does not work?

a = input() a = str(a) result = 0 count = 0 def summa_cifr(a, count, result): c = '' c = c + a[count] c = int(c) result = result + c if count < len(a): return summa_cifr(a,count+1, result) else: return result summa_cifr(a, count, result) print(result) 
  • 2
    Are you confused by the use of result as a global variable, as a function argument, and to return the value of a function? What happens when count = len(a) -1 ? PS Using lines is useless here - MBo pm
  • Thank you so much. - Spartak

2 answers 2

In my opinion, it was more useful to consider various recursive solutions to this problem.

Here is a one-line recursive solution that works with integers without converting to strings:

 def sum_digits(num): return num%10 + sum_digits(num//10) if num > 9 else num 

examples of work:

 In [17]: sum_digits(123) Out[17]: 6 In [18]: sum_digits(1234567) Out[18]: 28 In [19]: sum_digits(8) Out[19]: 8 
     a = input() a = str(a) def summa_cifr(a, count, result): c = '' c = c + a[count] c = int(c) result = result + c if count < len(a)-1: return summa_cifr(a,count+1, result) else: return result print(summa_cifr(a, 0, 0))