pythonfunctionglobal-variablesnameerror

Accessing A Global Variable Inside A Functon


I have a program (below) where I have define a function called function.

I know that you can access variables defined inside the function by defining them as a global variable if you want to access them outside the function.

Code

So, I defined a global variable inside the function. Then I tried to access it.

def function(x):
    
    global num_of_clust, clust_index
    clust_index = np.array([1,2,4])
    num_of_clust = len(clust_index)
    
    return x**2

if num_of_clust >= 1:
    
    print(2)

Issue

However, in my case, this doesn't seem to work.

I keep getting an error that says that num_of_clust is not defined, which it clearly is inside the function and is defined as a global variable.

NameError                                 Traceback (most recent call last)
<ipython-input-5-f629dd1943ba> in <module>
      7     return x**2
      8 
----> 9 if num_of_clust >= 1:
     10 
     11     print(2)

NameError: name 'num_of_clust' is not defined

I have another program with this same issue but it is more complicated so I wrote this test code in order to troubleshoot this issue.

Question

Does anyone have any insight or suggestions for why this is the case?


Solution

  • In your case num_of_clust is defined inside a function. But that function was never called.

    So you must either call it first or define num_of_clust outside the function.