Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

local variable referenced before assignment

Tags:

python

I'm new to python I found some answers to this question, but nothing could really help me.

here a the part of code with which I have problem:

batch_index=0 # initializing a globale variable, I've tried with global batch_index too 
..................................

def next_Training_Batch():
    if  batch_index < len(train_data):
        batch_index = batch_index + 1
        return train_data[batch_index-1], train_labels[batch_index-1]
    else :
        shuffle_data()
        batch_index = 0
        return train_data[batch_index], train_labels[batch_index]

when I call the function I get the following :

UnboundLocalError: local variable 'batch_index' referenced before assignment

I don't want to use a parameter in the function(as suggested in similar question) and to be honest I'm using number of "global" variable without have any errors, I don't get why I'm not allowed to evaluate it in the if statement? thanks for any hint !

like image 668
Engine Avatar asked Dec 23 '22 18:12

Engine


1 Answers

Add global batch_index to the beginning of the function and it will know that you're referring to the global variable not a local one.

batch_index=0 # initializing a globale variable, I've tried with global batch_index too 
...

def next_Training_Batch():
    global batch_index
    if batch_index < len(train_data):
        batch_index = batch_index + 1
        return train_data[batch_index - 1], train_labels[batch_index - 1]
    else:
        shuffle_data()
        batch_index = 0
        return tain_data[batch_index], train_labels[batch_index]
like image 84
TLOwater Avatar answered Jan 05 '23 23:01

TLOwater