0

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?

a121
  • 798
  • 4
  • 9
  • 20
Isse Nur
  • 53
  • 8

1 Answers1

2

You have to add a value to a variable before referencing it. So define first_digit before the if statement.

You can do something like this:

def sum(num):
    num_of_digits = len(str(num))

    # defining first_digit before if...
    first_digit = 0

    if num_of_digits != 1:
        # then referencing it will work
        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))
Abhay Salvi
  • 890
  • 3
  • 15
  • 39