简体   繁体   English

递归总和 function(“UnboundLocalError:赋值前引用的局部变量”)

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

The simple recursive sum function.简单的递归和 function。

It is supposed to add all digits of a number.它应该添加一个数字的所有数字。 For example sum(123) = 1 + 2 + 3 = 7例如 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.我取给定数字的第一个数字并将其添加到数字的 rest 的总和中。

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.所以在if语句之前定义first_digit

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 UnboundLocalError:赋值前引用了局部变量“sum” - UnboundLocalError: local variable 'sum' referenced before assignment UnboundLocalError:赋值odoo10之前引用了局部变量'sum' - UnboundLocalError: local variable 'sum' referenced before assignment odoo10 UnboundLocalError:仅在导入的函数中赋值之前引用的局部变量 - UnboundLocalError: local variable referenced before assignment in imported function only UnboundLocalError:在函数赋值之前引用了局部变量“n” - UnboundLocalError: local variable 'n' referenced before assignment in function Zip() 函数返回 UnboundLocalError:赋值前引用了局部变量“zip” - Zip() function returning UnboundLocalError: local variable 'zip' referenced before assignment UnboundLocalError:赋值之前(在函数的返回部分中)引用的本地变量“用户名” - UnboundLocalError: local variable 'username' referenced before assignment (in a return part of a function) 调用 function 时出现“UnboundLocalError:赋值前引用的局部变量” - "UnboundLocalError: local variable referenced before assignment" when calling a function UnboundLocalError:分配前已引用局部变量“ truebomb” - UnboundLocalError: local variable 'truebomb' referenced before assignment UnboundLocalError:分配前已引用局部变量“ cur” - UnboundLocalError: local variable 'cur' referenced before assignment UnboundLocalError:分配前已引用局部变量“ Counter” - UnboundLocalError: local variable 'Counter' referenced before assignment
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM