我编写了几个函数来计算样本响应的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))
return
更不容易引起问题。 - user2357112nps_score
函数之后,你可以添加nps_score.sample_size = 0
,然后你可以在nps_score
内外都用nps_score.sample_size
调用这个值。不过并不是说你应该这么做。 - Headcrabanother_function(first_function())
。但是,一般来说,不清楚为什么您不想执行这些赋值操作。任何其他方法都至少需要同样的工作量。全局变量(如果它们不是常量)会使程序逻辑更难理解。 - Karl Knechtel