You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python循环调用嵌套函数后无法继续迭代问题求助

问题分析与解决

你的问题出在main函数的for循环里——第一次处理switch1后,你执行了return(device),这个语句会直接终止main函数,导致循环无法继续迭代后续设备。

修复后的代码如下:

switch_list = ['switch1', 'switch2']

def main():
    print('We are in main')
    for device in switch_list:
        main_action = function1(device)
        # 移除循环内的return语句,避免提前终止函数

def function1(device):
    print(f'We are in function1 and the device name is {device}')
    function1_action = function2(device)

def function2(device):
    print(f'We are in function2 and the device name is {device}')
 
if __name__ == '__main__':
    main()

修改后运行输出会变成:

We are in main
We are in function1 and the device name is switch1
We are in function2 and the device name is switch1
We are in function1 and the device name is switch2
We are in function2 and the device name is switch2

如果后续需要收集每个设备的处理结果,可以在main函数里初始化一个列表,把每个设备的处理结果追加进去,最后在循环结束后返回这个列表,示例如下:

def main():
    print('We are in main')
    results = []
    for device in switch_list:
        result = function1(device)
        results.append(result)
    return results

内容的提问来源于stack exchange,提问作者JiggidyJoe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 17:38:26