Python可搜索元组添加yes/no循环时变量未定义问题求解
问题原因
- 字符串小写转换方法调用错误:获取用户输入后调用
lower时未添加括号,导致yesno存储的是lower方法本身的引用而非转换后的小写字符串,所有条件判断都会失败进入else分支,部分运行环境在递归调用时会触发作用域异常,报yesno未定义错误。 - 变量名不规范:使用Python内置类型名
tuple作为自定义变量名,会覆盖内置的元组类型,可能引发后续不可预期的错误。 - 冗余类型转换:
input()本身返回值就是字符串类型,不需要额外用str()包裹。
修正后的代码
# 替换为实际需要搜索的元组内容 search_tuple = ("apple", "banana", "orange", "grape") for i in search_tuple: print(i, end=' ') print() def main(): enter_name = input('Enter Search:') if enter_name in search_tuple: print('Yes its in there') else: print('No its not there') main() def yes_or_no(): # 给lower方法添加括号,正确执行小写转换 yesno = input("Would You Like to Search Again?").lower() yesChoice = ['yes', 'y'] noChoice = ['no', 'n'] if yesno in yesChoice: main() yes_or_no() elif yesno in noChoice: print("Goodbye") else: print("Please Enter either yes or no") yes_or_no() yes_or_no()
优化建议
原代码用递归实现重复询问逻辑,递归深度过高时会触发栈溢出错误,建议改用while循环实现更稳定:
search_tuple = ("apple", "banana", "orange", "grape") for i in search_tuple: print(i, end=' ') print() while True: enter_name = input('Enter Search:') if enter_name in search_tuple: print('Yes its in there') else: print('No its not there') # 处理是否继续搜索的逻辑 while True: yesno = input("Would You Like to Search Again?").lower() if yesno in ['yes', 'y']: break elif yesno in ['no', 'n']: print("Goodbye") exit() else: print("Please Enter either yes or no")
内容的提问来源于stack exchange,提问作者Dominic Matthews
相关产品推荐
相关产品推荐

