1number = 123 # the number you want summed up
2sum_of_digits = 0
3for digit in str(number):
4 sum_of_digits += int(digit)
5
6print(sum_of_digits) # printing the final sum of number
1digit_sum = lambda s: sum(int(digit) for digit in str(s)) #without recursion
2
3#sum of digits using recursion
4
5dsum = 0 # we define dsum outside of the function so its value isn't reset every time the function gets called recursivley
6
7def rdigit_sum(s):
8 global dsum # making dsum 'global' allows us to use it a function
9 if s: # checks if s has digits to add to dsum
10 dsum += s%10 # adds the current units digit to dsum
11 s = s//10 # removes the current units digit
12 else: # if there are no digits left
13 s = dsum # this block reassigns s to dsum, then resets dsum to 0 so dsum doesn't already have a value if this function is called more than once in a program
14 dsum = 0
15 return s
16 return rdigit_sum(s) # this is the 'recursive' part of the program that calls the function again
1number = 123 # the number you want to sum the digits of
2
3sum_of_digits = sum(int(digit) for digit in str(number))
4
5print(sum_of_digits)