0

My global variable count=0 is being changed in the function (method) below:

def Counter(counter,boolean=False)->int:
    if boolean:
        counter+=1
    else:
        counter=0

    return counter

and other functions uses Counter function:

def func1():
    global count
    count=Counter(count,True)
    print("func1:",count)

def func2():
    global count
    count=Counter(count,True)
    print("func2:",count)

When run these functions one more time like for loop

for _ in range(3):
    func1()
    func2()

the output is:

func1:1
func2:2
func1:3
func2:4
func1:5
func2:6

But output must be like this:

func1:1
func2:1
func1:2
func2:2
func1:3
func2:3

I researched different ways but could not find an answer. How can I do that?

colidyre
  • 4,170
  • 12
  • 37
  • 53
  • 1
    As a programmer you should try very, *very*, **very** hard not to use globals. – quamrana Aug 24 '20 at 12:49
  • 1
    That's pretty much the point of using a global variable. The solution (and better practice, anyway) is to not use a global variable. – DeepSpace Aug 24 '20 at 12:50
  • Also, I cannot understand why you think that the code you show *should* produce your desired output when `func1()` and `func2()` are essentially the same function. – quamrana Aug 24 '20 at 12:53
  • I don't want to use global variables, but I must to use only one variable for counter. I want a different counter to work in both functions. my func1 and func2 is already wrong, i don't know how can i fix. –  Aug 24 '20 at 13:00
  • the contents of the functions will change, I just wanted to ask in simple form. –  Aug 24 '20 at 13:02

1 Answers1

1

Why previous code didn't work?

The global keyword makes the counter variable accessible from both functions.
Using global variable is a bad-practice, don't do that.

How to achieve what you asked?

The following word assigns a counter for each of the functions, which modify it on each call.


def func1():
    func1.count+=1
    print("func1:", func1.count)

def func2():
    func2.count += 1
    print("func1:", func2.count)

func1.count=0
func2.count=0

for _ in range(3):
    func1()
    func2()

More about

What you ask, is how to use static-variable in a python function.
The term 'function static variable' refers to a variable that is accessible and owned by a function.
Python doesn't support static variables in a straight-forward manner such as in languages such as C# or Java, but there are other beautiful solutions in this thread, those are more complex and require the usage of decorators - so I didn't mention them.

Aviv Yaniv
  • 6,188
  • 3
  • 7
  • 22
  • Your code is useful for me, even if it doesn't give exactly what I want. I'll review these links. I think I'll use something similar to your answer. thanks for the solution. –  Aug 24 '20 at 14:04