简体   繁体   中英

Python returns global variable not defined

I have a method that inside it I scan an excel file in python and in another method I want to check an entry in a list in which I extracted the data from the excel sheet in the first method as follows:

def first():
    nodes_sh = xlrd.open_workbook(file_location)
    sh_method = nodes_sh.sheet_by_index(0)
    global node_data_inter
    node_data_inter = [[sh_method.cell_value(rr, co) for co in range(sh_method.ncols)] for rr in range(sh_method.nrows)] #O(rows*cols) # A loop to get all the data in the excel sheet of "Nodes Co-ordinates"
    global node_positions_ascending_inter
    node_positions_ascending_inter = dc.deepcopy(node_data_inter) #O(rows*cols)
    for rowss in range(len(node_positions_ascending_inter)): #O(rows)
        del (node_positions_ascending_inter[rowss][0:3])
        del (node_positions_ascending_inter[rowss][2])


def using_from_first_method():
    global node_positions_ascending_inter
    if node_positions_ascending_inter[0][0] == 1.25:
        print "Yes"

An error message is outputted when I type using_from_first_method()

NameError: global name 'node_positions_ascending_inter' is not defined

Why is it outputted as I already have defined node_positions_ascending_inter to be a global variable?

You need to declare node_positions_ascending_inter as a global in the using_from_first_method function. I got the below code (simplification) to run just fine.

def first():
    global node_positions_ascending_inter
    node_positions_ascending_inter = [1.25, 1.5, 1.3, 1.45]

def using_from_first_method():
    global node_positions_ascending_inter
    if node_positions_ascending_inter[0] == 1.25:
        print("Yes")

first()
using_from_first_method()

If you are still having issues maybe the problem lies in the filling of the array. Are you sure the first method is being called and successfully creating the global before the second tries to access it? Also, see the docs on globals here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM