简体   繁体   中英

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()```

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM