Home > Software engineering >  Using a returned array in another function
Using a returned array in another function

Time:01-19

I have a function that returns an array and a second function that is supposed to use this returned array, but the program returns saying array is not defined. How can I fix this problem?

def popt_reader(filename):
    with codecs.open(popt, 'r', encoding='utf-8') as data_file:
        rows, cols = [int(c) for c in data_file.readline().split() if c.isnumeric()]
        array = np.fromstring(data_file.read(), sep=' ').reshape(rows, cols)
        return array

def cleaner():
    out = []
    en_point = 0
    for i in range(1,len(array)):
        if np.all((array[i,1::] == 0)):
            pass
        else:
            out.append(array[i,:])
            en_point  = 1
    print(en_point)

cleaner(array)

CodePudding user response:

You never call the function that returns the array. Try this, just input your own file name

...

filename = "my_array_file_here.array"
array = popt_reader(filename)
cleaner(array)

CodePudding user response:

Variable array is defined within the popt_reader function and is not accessible within the cleaner function.

Add this line of code before cleaner(array) to make it work:

array = popt_reader(filename)

Which will assign output of popt_reader method to array variable.

Note that filename should also be defined beforehand

filename = "path to file"

CodePudding user response:

Just add a signature(parameter) to the function cleaner()

second one should be:

def cleaner(array):
    out = []
    en_point = 0
    for i in range(1,len(array)):
        if np.all((array[i,1::] == 0)):
            pass
        else:
            out.append(array[i,:])
            en_point  = 1
    print(en_point)

cleaner(array)
  • Related