简体   繁体   中英

Recursive sum function (“ UnboundLocalError: local variable referenced before assignment”)

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?

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM