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

Python函数无法遍历列表所有元素问题求助

问题分析与解决

你的问题核心出在greet_users函数的return语句位置:

  • 你把return(msg)放在了for循环内部,函数在遍历列表的第一个名字并执行打印后,就会触发return直接终止函数,后续名字根本没机会被处理,所以只会输出第一个名字。
  • 另外,msg = print(...)的写法完全多余,print()函数本身没有返回值(返回None),不需要把它的结果赋值给变量。

修正后的代码如下:

# function that should greet every user in the list of users.
def greet_users(names):
    for name in names:
        print(f"Hello {name}")

# How the user will quit the while loop.
print("Enter Q to exit")
total_users = [] 
# while loop to populate the list.
while True:
    user = input("Enter a user ")
    if user == "Q":
        break
    else:
        total_users.append(user)        

greet_users(total_users)

修改说明:

  • 移除了多余的msg变量赋值,直接在循环内执行print语句
  • 删掉了循环内的return语句,让for循环可以完整遍历整个用户列表,逐个打印问候语

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 17:17:01