在我的程序中,我需要一个计数器,但它只计数到一,而不是更高。这是我的代码:
# set a counter variable
c = 0
def counter(c):
c += 1
print(c)
if c == 10:
methodXY()
def do_something():
# here is some other code...
counter(c)
这是我的代码的重要部分。我想问题是 counter() 方法始终以 0 值开头,但我该如何解决这个问题呢?我的程序是否有可能“记住”我对 c 的值?希望你理解我的问题。顺便说一句:我完全是编程初学者,但我想变得更好
最佳答案
如果你想在函数中使用外部变量“c”,请将其写为global c。
def counter():
global c
c += 1
print(c)
if c == 10:
methodXY()
关于python - 如何在Python中创建全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57926334/