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

遍历函数对象而非返回值导致for循环无法获取迭代变量值的问题

Fixing Your For Loop Issue with the Function Return Value

Let's break down what's going wrong here and fix it step by step:

  1. You're iterating over the function itself, not its return value
    In your loop for blog in my_blogs:, my_blogs refers to the function object itself—not the tuple of blog strings it returns when you call it. Iterating over a function won't give you the content you passed in.

  2. You're calling the function after the loop runs
    Your my_blogs(blog_1, blog_2, blog_3) line comes after the loop finishes, so even if the loop was written correctly, it wouldn't have access to the returned values at that point.

Here's the corrected code:

blog_1 = "Hello"
blog_2 = "I am a man"
blog_3 = "i am living"

def my_blogs(*args):
    return args

# Call the function to get the tuple of blogs, then iterate over that return value
for blog in my_blogs(blog_1, blog_2, blog_3):
    print(blog)

What changed:

  • We moved the function call my_blogs(blog_1, blog_2, blog_3) directly into the for loop's iterable. Now we're looping over the tuple that the function returns, which contains your three blog strings.
  • Your function logic (using *args to capture variable arguments and returning them) is already correct—we just needed to make sure we're using its output properly.

If you want to reuse the returned collection later, you can also store it in a variable first:

all_blogs = my_blogs(blog_1, blog_2, blog_3)
for blog in all_blogs:
    print(blog)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 20:07:32