首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在一个python函数中访问另一个函数中的变量

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

Stack Overflow用户
提问于 2018-12-11 07:49:20
回答 1查看 15.6K关注 0票数 3

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

我不想返回第一个函数的结果,然后将其传递给另一个函数才能使用它们。

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

但它似乎抛出了错误。你知道怎么做到这一点吗?我不想使用Class并将这些变量作为Class变量。

代码语言:javascript
复制
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))
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-12-11 07:52:27

你必须声明变量是全局的,然后才能使用它。如下所示:

代码语言:javascript
复制
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

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

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

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

代码语言:javascript
复制
global var1, var2, var3 #etc.
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53715423

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档