代码之家  ›  专栏  ›  技术社区  ›  Baktaawar David Maust

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

  •  0
  • Baktaawar David Maust  · 技术社区  · 7 年前

    我编写了几个函数来计算一个样本响应的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))
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   Eb946207 mourshad    7 年前

    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 var1, var2, var3 #etc.