ISBN-10/ISBN-13转换代码问题:输入处理后返回空列表求助
ISBN转换代码修复:从空列表到正常输出
需求说明
获取用户输入的ISBN-10/ISBN-13,存入数据集后检查每个输入的长度,将ISBN-13转换为ISBN-10,最终得到一个纯ISBN-10的列表。
问题描述
运行下方代码后始终返回空列表,无法定位错误原因:
import pyisbn alist = [] def get_dataset(): while True: try: dataset = [str(_) for _ in input("\nEnter Book ID(s): ").replace(',', ' ').split()] except ValueError: print("\nInvalid Input") continue for _ in range(0, len(dataset)): if len(_) == 10: alist.append(dataset) if len(_.replace('-', '')) == 13: alist.append(pyisbn.convert(dataset)) if len(dataset) < 1: print("\nPlease enter at least 1 Book ID.") else: return alist print(get_dataset())
排查尝试
- 将for循环移至数据集长度检查后,输入程序直接结束
- 将代码移出try循环,出现“Object of type 'int' has no len”错误
- 将代码移出函数,问题仍未改善
错误分析
- 缩进错误:try块内的for循环缩进在
continue之后,导致永远不会执行——一旦进入try块,要么正常获取dataset,要么触发except,而for循环被continue完全挡住,根本跑不到。 - 遍历对象错误:用
for _ in range(0, len(dataset))遍历的是索引数字,不是ISBN元素,所以len(_)会报错(int类型没有长度属性),逻辑上也没处理实际的ISBN值。 - 添加对象错误:
alist.append(dataset)是把整个输入的数据集列表加进去,而不是单个ISBN或转换后的结果。 - 全局变量风险:
alist定义在函数外部,函数直接修改全局变量,容易导致状态混乱,多次调用还会累积旧数据。
修复后的代码
import pyisbn def get_dataset(): alist = [] # 将结果列表移到函数内部,避免全局变量干扰 while True: try: # 处理输入:去除空格、拆分、过滤空项 input_str = input("\nEnter Book ID(s): ").strip() dataset = [item.strip() for item in input_str.replace(',', ' ').split() if item.strip()] except Exception as e: print("\nInvalid Input") continue if not dataset: # 检查输入是否为空 print("\nPlease enter at least 1 Book ID.") continue # 遍历每个ISBN元素处理 for isbn in dataset: cleaned_isbn = isbn.replace('-', '') # 处理ISBN-10 if len(cleaned_isbn) == 10: alist.append(isbn) # 处理ISBN-13并转换为ISBN-10 elif len(cleaned_isbn) == 13: try: converted_isbn = pyisbn.convert(isbn) alist.append(converted_isbn) except pyisbn.InvalidISBNError: print(f"\nInvalid ISBN-13: {isbn},无法转换") return alist print(get_dataset())
修复要点
- 修正缩进,让for循环能正常执行
- 遍历dataset中的每个ISBN元素,而非索引数字
- 先清理ISBN的连字符再判断长度,避免格式干扰
- 添加转换错误捕获,处理无效ISBN的情况
- 将结果列表移到函数内部,避免全局变量的状态混乱
内容的提问来源于stack exchange,提问作者Mr. P
相关产品推荐
相关产品推荐

