Search code examples
pythonloopscountercounting

How to create a global variable in python


In my program I need a counter, but it just counts to one and not higher. Here is my code:

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

this is the important part of my code. I guess the problem is that the method counter() starts with the value 0 all the time, but how can I fix that? Is it possible that my program "remembers" my value for c? Hope you understand my problem. Btw: I am a totally beginner in programming, but I want to get better


Solution

  • You always call the function with the value 0 (like you expected). You can return "c" and call it again.

    Look:

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