1

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

gmuraleekrishna
  • 3,375
  • 1
  • 27
  • 45
  • You should look into scope. You are only adding 1 to the function argument `c` within the function `counter`. Remove the argument `c` from the parameter list and the call site and then you should see what you expect. But do google and research scope. – Carl Sep 13 '19 at 15:23
  • Possible duplicate of [Understanding Python's call-by-object style of passing function arguments](https://stackoverflow.com/questions/10262920/understanding-pythons-call-by-object-style-of-passing-function-arguments) – walnut Sep 13 '19 at 15:35

2 Answers2

1

If you want to use outer variable "c" inside your function, write it as global c.

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

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)