我如何声明一个变量并在python的2个函数中访问它

时间:2019-12-19 19:34:25

标签: python function for-loop count increment

在Python中,我是python的新手,我不知道它是从一周前开始的。我想计算执行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()```

1 个答案:

答案 0 :(得分:1)

您需要将计数器定义为全局变量。老实说,更好的方法是使用Python Decorators并修饰您的函数。但实际上,您正在这样做。

count = 0

def example():
    global count
    count+=1

def example2():
    global count
    count+=1

example()
example(2)
print(count)