我写了几个函数来计算样本响应的NPS和误差幅度。
我不想返回第一个函数的结果,然后将其传递给另一个函数才能使用它们。
所以我希望创建全局变量,这些变量可以在它创建的函数之外使用,这样它就可以在其他函数中使用,而不需要传递它们。
但它似乎抛出了错误。你知道怎么做到这一点吗?我不想使用Class并将这些变量作为Class变量。
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))发布于 2018-12-11 07:52:27
你必须声明变量是全局的,然后才能使用它。如下所示:
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关键字放在函数的开头。它不需要紧跟变量的更改,并且只需要一次。
要将多个变量声明为全局变量,请执行以下操作:
global var1, var2, var3 #etc.https://stackoverflow.com/questions/53715423
复制相似问题