Python混合全局变量和局部变量?

时间:2019-01-11 00:00:55

标签: python python-3.x variables variable-assignment

我将全局变量'i'初始化为0和函数定义。 在def中,我想将局部'j'初始化为全局'i',然后将1分配给全局'i',但是编译器认为当我将1分配给'i'时,我对其进行了初始化。

这不起作用:

i = 0
def doSomething():
    j = i # compiler throws UnboundLocalError here
    i = 1

这有效:

i = 0
def doSomething():
    j = i

1 个答案:

答案 0 :(得分:0)

在修改之前,您需要在函数中声明全局变量。

 i = 0
def doSomething():
    global i #needed to modify the global variable.
    j = i # compiler throws UnboundLocalError here
    i = 1
相关问题