如何在另一个函数中访问一个python函数中的变量

Bak*_*war 3 python

我编写了几个函数来计算样本响应的 NPS 和误差幅度。

我不想从第一个函数返回结果,然后将它传递给另一个函数以便能够使用它们。

所以我希望创建全局变量,这些变量可以在它创建的函数之外使用,以便它可以在其他函数中使用而无需传递它们。

但它似乎抛出错误。知道如何实现这一目标吗?我不想使用类并将这些变量作为类变量。

def nps_score(responses): 
    """Function to get the NPS score from the 
     Survey responses 

    """
    global sample_size = len(responses)
    global promoters_proportion = sum([1 for x in responses if x >=9])/sample_size
    global detractors_proprotion= sum([1 for x in responses if x<=6])/sample_size

    global sample_NPS= promoters_proportion - detractors_proportion

    print("Sample Net Promoter Score(NPS) is {} or {}%".format(sample_NPS,sample_NPS*100))



def moe():
    """ Calculate the margin of error
    of the sample NPS 

    """

    # variance/standard deviation of the sample NPS using 
    # Discrete random variable variance calculation

    sample_variance= (1-sample_NPS)^2*promoters_proportion + (-1-sample_NPS)^2*detractors_proportion

    sample_sd= sqrt(sample_variance)

    # Standard Error of sample distribution

    standard_error= sample_sd/sqrt(sample_size)

    #Marging of Error (MOE) for 95% Confidence level
    moe= 1.96* standard_error

    print("Margin of Error for sample_NPS of {}% for 95% Confidence Level is: {}%".format(sample_NPS*100,moe*100))
Run Code Online (Sandbox Code Playgroud)

Eb9*_*207 5

您必须将变量声明为全局变量,然后使用它。像这样:

def add_to_outside():
    global outside #say that it is global
    outside = 1 #now create it!

def see_it():
    global outside #say that it is global
    print(outside)

##As shown:
add_to_outside()
see_it()
#output: 1
Run Code Online (Sandbox Code Playgroud)

global开头的关键字使函数中该名称的所有变量都引用全局值。你不会说一个变量是全局的,并在同一个语句中改变它。

此外,只将global关键字放在函数的开头。它不需要在变量更改旁边,并且只需要一次。

要声明多个全局变量,请执行以下操作:

global var1, var2, var3 #etc.
Run Code Online (Sandbox Code Playgroud)