如何对比输入与列表内容并处理非法输入?
输入匹配循环函数的问题修复与优化
Hey there! Let's break down your code and get it working smoothly—there are a few small issues that are keeping it from behaving as expected, plus some tweaks to make it more user-friendly.
原代码中的关键问题
- 变量名不匹配:函数参数是
tested_list,但你在循环里用了a_list,这会直接抛出NameError,因为a_list从未定义。 - 拼写错误:
corect_input应该是correct_input(少了一个'r'),虽然Python不会报错,但这会降低代码可读性。 - 冗余的异常捕获:
try-except块捕获ValueError是没用的,因为input()返回的永远是字符串,str.lower()也不会抛出这个异常。 - 无反馈的无限循环:如果用户输入的内容不在列表中,程序会一直重复请求输入,但不会告诉用户哪里错了,体验很差。
- 无效的
else块:else里设置correct_input = False完全没必要,因为while循环的条件已经是not correct_input,没找到匹配时循环自然会继续。
修正后的代码
def get_input(tested_list): correct_input = False while not correct_input: my_input = input("Enter here: ").lower() # 遍历传入的tested_list,而不是未定义的a_list for line in tested_list: # 确保line至少有3个元素,避免IndexError if len(line) >= 3 and my_input == line[2].lower(): return my_input # 如果走到这里,说明输入不匹配,给用户提示 print("Oops, that input isn't in our list. Please try again!")
关键修改说明
- 修正了参数和循环变量的匹配问题,现在用传入的
tested_list进行遍历。 - 增加了
len(line) >= 3的判断,避免如果列表中的元素不足3个时抛出IndexError。 - 移除了多余的
try-except块,简化代码逻辑。 - 添加了用户反馈:当输入不匹配时,明确告诉用户需要重新输入。
- 修正了变量拼写错误,提升代码可读性。
这样修改后,函数不仅能正常运行,还能给用户清晰的指引,避免无意义的无限循环。
内容的提问来源于stack exchange,提问作者michal w
相关产品推荐
相关产品推荐

