How to access a variable in one python function in another function

Question:

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))
Asked By: Baktaawar

||

Answers:

You have to declare the variable to be global, then use it. Like so:

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

The keyword global at the start makes all variables of that name in the function reference the global values. You don’t say a variable is global and change it in the same statement.

Also, only put the global keyword at the start of the function. It doesn’t need to be next to the changes to the variables, and is only needed once.

To declare multiple variables global, do it like this:

global var1, var2, var3 #etc.
Answered By: Eb946207
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.