Python if条件清除、匹配结果输出不全、输入残留问题修复
Python姓名搜索程序两处Bug修复方案
问题原因
- 多匹配项仅显示第一个:你将用户确认逻辑的
while True循环写在了遍历姓名列表的for循环内部,匹配到第一个符合条件的姓名后就直接进入确认死循环,不会继续执行后续列表遍历,因此其余匹配项无法输出。另外result = print(x)属于无效写法,print()本身无返回值,赋值给变量没有实际作用。 - 输入重复读取:你用递归调用
other()的方式处理重新输入的逻辑,但递归调用时没有终止当前函数内正在运行的for循环、while循环,旧调用栈的输入逻辑会在递归执行完后继续运行,就会出现连续弹两次输入框、读取残留旧输入的问题。
修复思路
- 把匹配逻辑和确认逻辑拆分:先遍历完整个姓名列表,收集所有符合搜索关键词的结果统一展示,不要匹配到一个就打断遍历
- 去掉递归实现的重新输入逻辑,改用外层循环控制流程,从根源避免调用栈残留导致的逻辑异常
- 补充无匹配结果的分支提示,优化交互体验
修复后可直接运行的代码
import time def start(): data = ["Lucas_Miguel", "João_Batista", "Rafael_Gomes", "Bruna_Santos", "Lucas_Denilson"] print("1 - Check Name") print("2 - Register a New Name") option = input("Choose an option: ") if option == "1": while True: name = input("Type the first name: ") # 先收集所有匹配结果 match_results = [x for x in data if name in x] if not match_results: print("No matching name found.") else: # 统一输出所有匹配项 for res in match_results: print(res) # 所有结果输出完再走确认逻辑 while True: confirm = input("Is the name you want in the options? (Yes/No): ") if confirm == "Yes": # 找到目标直接退出所有循环 return if confirm == "No": try_again = input("Do you want to write again? (Yes/No): ") if try_again == "Yes": # 跳出当前确认循环,回到搜索输入步骤 break else: # 不重试直接返回主菜单 return # 输入不是Yes/No就提示重新输入 print("Please input Yes or No") else: print("Option not available") time.sleep(1) return start() start()
修复后测试:搜索关键词
Lucas时会同时输出Lucas_Miguel和Lucas_Denilson两个匹配项;选择重新输入时不会出现重复弹输入框的问题。
内容的提问来源于stack exchange,提问作者Maracujá
相关产品推荐
相关产品推荐

