Python中查询无匹配时print语句重复执行两次的修复咨询
修复搜索名称时重复输出错误提示的问题
问题原因
原代码在for循环内部的else分支中,每遍历到一行不匹配的内容就会打印一次错误提示。如果文件中有N行不匹配目标名称,就会重复输出N次"Unable to find your name"。
修复方案一:使用标志位追踪匹配状态
if ask.lower() == 'open': with open(filename, 'r') as f: contents = f.read().splitlines() search_name = input("What is your name? ") found = False for line in contents: if search_name in line: # 用in关键字比find更直观 print(line) found = True # 若只需匹配第一个结果,可添加break终止循环 # break if not found: print("Unable to find your name")
- 逻辑说明:初始化
found标志位记录是否找到匹配项,遍历过程中找到匹配行时更新标志位;循环结束后统一判断是否输出错误提示,确保只打印一次。
修复方案二:先收集所有匹配结果
if ask.lower() == 'open': with open(filename, 'r') as f: contents = f.read().splitlines() search_name = input("What is your name? ") # 筛选所有包含目标名称的行 matched_lines = [line for line in contents if search_name in line] if matched_lines: for line in matched_lines: print(line) else: print("Unable to find your name")
- 逻辑说明:先用列表推导式收集所有匹配行,再通过判断列表是否为空来决定输出匹配内容还是错误提示,避免循环内重复输出。
内容的提问来源于stack exchange,提问作者user19704156
相关产品推荐
相关产品推荐

