遍历函数对象而非返回值导致for循环无法获取迭代变量值的问题
Let's break down what's going wrong here and fix it step by step:
You're iterating over the function itself, not its return value
In your loopfor blog in my_blogs:,my_blogsrefers 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.You're calling the function after the loop runs
Yourmy_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 theforloop's iterable. Now we're looping over the tuple that the function returns, which contains your three blog strings. - Your function logic (using
*argsto 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

