I wrote a couple of functions to calculate the NPS and Margin of error of a sample responses.
I don't want to return the result from first function and then passing it to another function to be able to use them.
So I was looking to create global variables which can be available outside the function it's created so that it can be used in other function without having to pass them.
But it seems to throw the error. Any idea how to achieve this? I don't want to use a Class and make these variables as Class variables.
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))
returnis much less likely to cause problems than global variables.nps_scorefunction, you can addnps_score.sample_size = 0, then you can address that asnps_score.sample_sizeboth inside and outsidenps_score. Not saying that you should, though.another_function(first_function()). However, in general, it's not clear why you wouldn't want to do these assignments. Anything else will be at least as much work. Global variables (if they aren't constant) make it harder to reason about the program logic.