Skip to main content
 首页 » 编程设计

python之如何在 Python 中使用全局变量

2025年05月04日23lhb25

我不确定为什么当我声明一个全局变量时它不起作用...

first_read = True 
 
def main(): 
 
    if (first_read == True): 
        print "hello world" 
        first_read = False 
 
    print 'outside of if statement' 
 
if __name__ == '__main__': 
    main() 

我的回溯显示以下错误:

Traceback (most recent call last): 
   File "true.py", line 12, in <module> 
      main()    
   File "true.py", line 5, in main 
     if (first_read == True):  
UnboundLocalError: local variable 'first_read' referenced before assignment 

请您参考如下方法:

您必须将变量定义为全局变量:

first_read = True 
 
def main(): 
    global first_read 
    if (first_read == True): 
       print "hello world" 
       first_read = False 
 
    print 'outside of if statement' 
 
if __name__ == '__main__': 
    main()