2015-12-17 43 views
0

前引用了我新的Python试图执行此代码:unboundlocalerror局部变量 'I' 分配

def dubleIncrement(): 
    j = j+2 

def increment(): 
    i = i+1 
    dubleIncrement() 

if __name__ == "__main__": 

    i = 0 
    j = 0 
    increment() 
    print i 
    print j 

但收到此错误:

unboundlocalerror local variable 'i' referenced before assignment 

任何人有任何想法,为什么i是不是全局的

+1

因为您没有使用'global'关键字吗? – Hacketo

+0

因为我没有在'increment'范围内定义' – ZdaR

+0

'def increment():global i' –

回答

1

声明global关键字在你的函数中访问全局而不是本地变量。即

def dubleIncrement(): 
    global j 
    j = j+2 

def increment(): 
    global i 
    i = i+1 

注意,当你在if声明声明i = 0j = 0,这是设置一个全局变量,但因为它是任何功能范围之外,该global关键字是没有必要在这里使用。

理想情况下,您应尽量避免使用全局变量,并尝试将变量作为参数传递给函数(想想当您决定在其他函数中再次使用变量名称ij时会发生什么 - 可能发生丑陋的碰撞!)。以下是编写代码的更安全的方法:

def dubleIncrement(x): 
    x = x+2 
    return x 

def increment(x): 
    x = x+1 
    return x 

if __name__ == "__main__": 
    i = 0 
    j = 0 
    i = increment(i) 
    j = dubleIncrement(j) 
    print i 
    print j 
相关问题