python - 我如何声明一个变量并在 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()```
解决方案
您需要将计数器定义为全局变量。老实说,更好的方法是使用 Python 装饰器并装饰你的函数。但本质上你正在这样做。
count = 0
def example():
global count
count+=1
def example2():
global count
count+=1
example()
example2()
print(count)
推荐阅读
- object - 应用程序启动方法中的异常——带有 Intellj 的 JavaFx
- angular - 地图在 Angular RxJs 中不起作用
- sql - bcp 未从任务调度程序运行
- java - 从 OkHttp 转到 HttpURLConnection
- c++ - 添加排序袋 C++
- python - 多处理 API
- primefaces - Primefaces 步骤跳过对 primefaces 文件上传器的验证
- laravel - 从目录中获取文件
- c++ - Xcode iOS 目标。模拟器崩溃并显示消息“dyld:未加载库(...)缺少所需的代码签名”
- python-3.x - LIBUSB_ERROR_BUSY [-6] 使用 LibUSB1 使用 Python 3.9 发送基本数据包