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
相关产品推荐
相关产品推荐

