Write a function that takes in a nonnegative integer and sums its digits. (Using floor division and modulo might be helpful here!)def sum_digits(n):"""Sum all the digits of n.>>> sum_digits(10) # 1 + 0 = 11>>> sum_digits(4224) # 4 + 2 + 2 + 4 = 1212>>> sum_digits(1234567890)45 """

Respuesta :

Answer:

def sum_digits(n):

   sum=0

   while n>0:

       num=n%10     #will store digits of number

       sum+=num    #sums the digits

       n=int(n/10)

   return sum  #sum of digits is returned

Explanation:

In the above method , n is the number whose digit sum is to be returned. Sum is the variable which will store the sum of digits. Then a while loop will be executed until n is greater than 0 then num will store the individual digits of number and those digits will be added in sum variable. After that, n will be divided by 10. As we want only int variable we will typecast it into int.