使用循环保存多用户输入:好友名单程序开发问题
我想要编写一个小程序,让用户输入其好友的名字。用户完成输入后按Enter键,循环停止并以编号列表形式打印每个好友的名字。程序运行示例如下:
Enter the names of your best friends
Friends Name (Enter to quit): Friend1
Friends Name (Enter to quit): Friend2
Friends Name (Enter to quit): (按Enter)
My best friends are:
Friend1
Friend2
以下是我目前的不完整代码草稿:
while True: friendname = input("Friends Name (Enter to quit): ") list = str(friendname)" #something here keeps the names if friendname == "": break print (list)
我的问题是,不知道如何保存输入的名字并将其以列表形式打印出来。
嗨,我来帮你搞定这个问题!你的代码里主要有两个小问题:一是错误地把存储容器初始成了字符串(还犯了语法错误),二是没找到合适的方式收集多个名字。咱们一步步修正:
1. 先准备一个空列表存名字
首先得创建一个空列表,而不是字符串——列表天生就是用来存储多个值的。另外注意别用list当变量名,这是Python的内置类型,用它当变量名会搞乱内置功能,换成friends既清晰又安全。
2. 循环收集输入的名字
在循环里,每次用户输入非空的名字时,就把它添加到列表里;如果用户直接按回车(输入为空),就跳出循环停止收集。
3. 用编号列表打印结果
循环结束后,用enumerate()函数遍历列表,它能帮你生成从指定数字开始的编号(这里设start=1,让编号从1开始),刚好能输出你想要的编号列表格式。
完整可运行代码
print("Enter the names of your best friends") # 初始化空列表,用来存好友名字 friends = [] while True: friend_name = input("Friends Name (Enter to quit): ") # 输入为空时,退出循环 if friend_name == "": break # 把非空的名字添加到列表里 friends.append(friend_name) # 打印最终结果 print("\nMy best friends are:") # 用enumerate生成从1开始的编号,遍历列表输出 for index, name in enumerate(friends, start=1): print(f"{index}. {name}")
运行效果
运行这段代码后,会和你想要的示例完全一致:
Enter the names of your best friends
Friends Name (Enter to quit): Friend1
Friends Name (Enter to quit): Friend2
Friends Name (Enter to quit):My best friends are:
- Friend1
- Friend2
这样就完美实现你想要的功能啦!
内容的提问来源于stack exchange,提问作者user11621936

