首页 > 解决方案 > 为什么我的代码只在运行第一个函数时才起作用,而第二个函数给我一个赋值前引用的变量?

问题描述

我已经尝试更改问题的变量 thinkig 的名称,但这并没有解决它。我正在尝试计算输入到 get_numbers 函数中的数字的加法持久性和乘法持久性以及加法和乘法根。对于additive_calculator 和multiplicative_calculator 函数,无论我调用第一个函数,但第二个函数在打印语句中给我一个错误,说根的值,我在这种情况下称为total 和total2,在赋值之前给了我一个引用错误。我不知道如何解决此错误。`在此处输入代码

from functools import reduce
def get_numbers():
    num = (int(input("Please enter an integer(negative integer to quit):")))
    nums = [int(a) for a in str(num)]
    return(nums)

nums = get_numbers()
print(nums)


def additive_calculator(nums):
    print("Additive loop")
    counter = 0
    while len(nums) > 1:
        for num in nums:
            len(nums)
            total = 0
            total = sum(nums)
            list.clear(nums)
            nums = [int(a) for a in str(total)]
            print("sum:", total)
            print(len(nums))
        counter = counter + 1
    print("Additive persistence", counter,",", "Additive Root:", total)
print("DONE")
            



def multiplicative_calculator(nums):
    print("multiplicative loop")
    counter = 0
    while len(nums) > 1:
        for num in nums:
            len(nums)
            total2 = 0
            total2 = reduce(lambda x, y: x*y,(nums))
            list.clear(nums)
            nums = [int(a) for a in str(total2)]
            print("sum:", total2)
            print(len(nums))
        counter = counter + 1
    print("multiplicative persistence", counter,",", "multiplicative Root:", total2)
print("DONE")


multiplicative_calculator(nums)            
additive_calculator(nums)

标签: pythonfunction

解决方案


如果您在函数中的任何位置分配给变量,则该变量被视为局部变量(除非声明为全局变量或非局部变量)。函数运行时您是否实际执行分配并不重要;在分配给它的函数中有一些语句就足够了。

例如,在下面的函数中,a仅当参数b为 true 时才分配给变量,但a如果不分配给它(whenb为 false),它仍然是局部变量。

def f(b):
    if b:
        a = "foo"
    return a


f(True)   # -> "foo"
f(False)  # error

循环也是如此。如果您分配给循环体中的变量或循环中的for变量,则即使您不执行循环体,该变量也是局部变量。如果你执行body,变量被赋值,读取它是安全的,但是如果你不执行body,变量没有被初始化,读取它是错误的。

def f(x):
    for a in x:
        pass
    return a


f([1, 2, 3])  # -> 3
f([])         # error

在您的代码中,如果nums为空,total2则永远不会分配给。它仍然是一个局部变量,因为在代码中对其进行了赋值——语句永远不会执行并不重要——但是如果你没有赋值,读取变量是错误的。

total2修复很简单:无论是否进入循环体,都要确保初始化。

def multiplicative_calculator(nums):
    print("multiplicative loop")
    counter = 0
    total2 = 0  # move initialisation of total2 here
    while len(nums) > 1:
        # same code as before...
    # when you get here, total2 is initialised whether you
    # entered the loop or not.
    print("multiplicative persistence", counter,
          ",", "multiplicative Root:", total2)

推荐阅读