我的全局变量没有更新,它的全部打印为0。为什么会发生这种情况?全球变量不良练习吗?
counter = 0
def count():
global counter
print(counter)
counter += 1
return counter
if __name__ == "__main__":
count()
您首先打印它,然后仅更改其值。如果您移动
counter += 1
上面的 print
行,您会看到它打印为1
。
它只会打印一次,而不是连续打印。由于您没有在某种类型的循环中调用count
,因此只会更新和打印结果。
- 您正在返回更新的计数器值,因此只需打印即可。
counter = 0
def count():
global counter
print(counter)
counter += 1
return counter
if __name__ == "__main__":
print(count())
添加后必须打印以查看添加
counter = 0
def count():
global counter
counter += 1
print(counter)
return counter
if __name__ == "__main__":
count()
您需要某种永久存储来记住运行之间counter
的值。例如,
import os
counter_file = "..." # some file name
def count():
global counter
print(counter)
counter += 1
return counter
if __name__ == "__main__":
if not os.path.exists(counter_file):
counter = 0
else:
with open(counter_file) as f:
counter = int(f.read())
count()
with open(counter_file) as f:
print(counter, file=f)