gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:40:06 27 4
gpt4 key购买 nike

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

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()

关于python - 如何在 Python 中使用全局变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45581133/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com