NameError:name' freshdatapoly'未定义 - 先前定义的变量?

时间:2016-04-03 08:16:21

标签: python variables numpy tuples

我正在尝试编写一个代码来划分以二进制形式给出的两个多项式(分别为newdata和proofin)。但是,当我运行代码时,我得到:

NameError: name 'freshdatapoly' is not defined

这让我感到困惑,因为我认为我确实定义了,甚至附加了它(似乎没有错误)。我怀疑之后可能会发生同样的事情,因为' proofpoly'也。这是代码:

import numpy as np

def transformation_for_numpy_of_o():
    newdata = ("101001")
    freshdata = list(newdata)
    freshdatapoly = []

    for n in freshdata:

        if n == 1:
            freshdatapoly.append(1.0)

        if n == 0:
            freshdatapoly.append(0.0)



def transformation_for_numpy_of_proof():
    proofin = ("101001")
    proofing = list(proofin)
    proofpoly = []

    for n in proofing:

        if n == 1:
            proofpoly.append(1.0)

        if n == 0:
            proofpoly.append(0.0)



def total():

    # Based on http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.polydiv.html

    transformation_for_numpy_of_o()
    transformation_for_numpy_of_proof()
    numer = np.array(freshdatapoly)
    denomin = np.array(proofpoly)
    answer = np.polydiv(numer, denomin)
    print (answer)

total()

1 个答案:

答案 0 :(得分:1)

freshdatapolytransformation_for_numpy_of_o()函数中的 local 变量。它只存在于该函数中。

使用return从函数返回该值,然后将其分配给total()中的新本地:

def transformation_for_numpy_of_o():
    newdata = ("101001")
    freshdata = list(newdata)
    freshdatapoly = []

    for n in freshdata:

        if n == 1:
            freshdatapoly.append(1.0)

        if n == 0:
            freshdatapoly.append(0.0)

    return freshdatapoly

total()

o_transformed = transformation_for_numpy_of_o()
# ...
numer = np.array(o_transformed)

您也需要为proofpoly中使用的transformation_for_numpy_of_proof()执行此操作;这是 函数中的局部变量,而不是total()可用的局部变量,除非您将其返回。