Search code examples
pythonfunctionfor-loopcountincrement

how i can declare a variable and access it inside 2 functions in python


In Python, I am new with python, I don't know about it , started a week ago. I want to count how many times I am executing fuction1.

       the_list = ["1","2","3"]

       for i in the_list:
           print(i)

           function1(i)


   def function1(the_list):
       the_list2 = ["a","b"]
       count = 0

        "''here I i am defining the count so the value is
       getting reset whever it is exiting for loop"""

        for j in the_list2:
           print(j) 
           count +=1
       print(">>",count)
       #here i wanna count how manny times we are running this print statment?


   function()```

Solution

  • You need to define your counter as a global variable. Honestly the better way to do this is to use Python Decorators and just decorate your function. But essentially you are doing this.

    count = 0
    
    def example():
        global count
        count+=1
    
    def example2():
        global count
        count+=1
    
    example()
    example2()
    print(count)