分配前引用的局部变量

发动机

我是python的新手,我找到了此问题的一些答案,但没有什么可以真正帮助我。

这是我遇到问题的一部分代码:

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]

当我调用该函数时,我得到以下信息:

UnboundLocalError: local variable 'batch_index' referenced before assignment

我不想在函数中使用参数(类似问题的建议),说实话,我使用的是“全局”变量,没有任何错误,我不明白为什么我不允许这样做在if语句中评估它?感谢您的任何提示!

TLOwater

添加global batch_index到函数的开头,它将知道您是指全局变量而不是局部变量。

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]

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

什么是“分配前引用的局部变量”

分配前引用的局部变量X

分配前已引用局部变量“ ...”

分配前引用的局部变量-错误

难以理解“分配前引用的局部变量”

UnboundLocalError:分配前已引用局部变量“ opTuple”

无局部变量,但警告:分配前已引用

pygame-分配前引用的局部变量

UnboundLocalError:分配前已引用局部变量“ req”

ipython%timeit“分配前引用了局部变量'a'

UnboundLocalError:分配前引用了局部变量“pin”

Django上下文:分配前引用的局部变量

简单函数问题,分配前已引用局部变量

python err:分配前引用的局部变量

Python-分配前引用的局部变量

在if语句后出现“ UnboundLocalError:分配前引用的局部变量”

Python 3:UnboundLocalError:分配前引用的局部变量

分配前已引用局部变量“列表”

UnboundLocalError:分配前已引用局部变量“ cursor”

UnboundLocalError:分配前已引用局部变量“键”

UnboundLocalError:分配前已引用局部变量“ slcount”

While循环:UnboundLocalError:分配前引用的局部变量

Python错误-分配前的局部变量引用

Django:UnboundLocalError:分配前已引用局部变量“ company”

UnboundLocalError:分配前已引用局部变量“ ticketCost”

UnboundLocalError:分配前已引用局部变量“ settingsText”

UnboundLocalError:分配前已引用局部变量“ response”

UnboundLocalError:分配前已引用局部变量“事件”(PYGAME)

分配前引用的python电报bot局部变量