如何在 python 中创建全局变量

How to create a global variable in python

在我的程序中我需要一个计数器,但它只计数到 1 而不是更高。这是我的代码:

# 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 开头,但我该如何解决呢?有没有可能我的程序"remembers"我对c的价值?希望你能理解我的问题。顺便说一句:我完全是编程初学者,但我想变得更好

您总是使用值 0 调用函数(如您所料)。你可以 return "c" 并再次调用它。

看:

# set a counter variable
c = 0

def counter(c):

    c += 1
    print(c)
    return c



def do_something(c):

    c=counter(c)
    return c

for i in range(10):    
    c=do_something(c)

如果你想在你的函数中使用外部变量"c",写成global c.

def counter():
    global c
    c += 1
    print(c)
    if c == 10:
        methodXY()