首页 > 解决方案 > 我如何声明一个变量并在 python 的 2 个函数中访问它

问题描述

在Python中,我是python新手,我不知道,一周前开始的。我想计算我执行了多少次函数1。

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

标签: pythonfunctionfor-loopcountincrement

解决方案


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

count = 0

def example():
    global count
    count+=1

def example2():
    global count
    count+=1

example()
example2()
print(count)

推荐阅读