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