The simple recursive sum function.
It is supposed to add all digits of a number. For example sum(123) = 1 + 2 + 3 = 7
It works by tail recursion. I take the first digit of the given number and add it to the sum of the rest of the digits.
def sum(num):
num_of_digits = len(str(num))
if num_of_digits != 1:
first_digit = int(num / pow(10, num_of_digits - 1))
rest = num - int(num / pow(10, num_of_digits - 1)) * pow(10, num_of_digits - 1)
return first_digit + sum(rest)
else:
return first_digit
print(sum(123))
the error
UnboundLocalError: local variable 'first_digit' referenced before assignment
My question is why is the code not working?