[英]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.