Python统计高尔夫得分出现str与int比较TypeError如何解决
错误原因
你遇到的TypeError: '<' not supported between instances of 'str' and 'int'报错,是因为从文本文件读取的得分都是字符串格式,没有转换为整数就直接和数字280做大小比较。除此之外你的代码还存在缩进错误、逻辑错误等多处问题,完整修正方案如下:
修正后的代码
def open_and_read_golf_scores(): scores = [] # 用with上下文管理器自动处理文件关闭,避免资源泄漏 with open("golfscores.txt", "r") as raw_scores: for current_line in raw_scores: current_line = current_line.strip() if not current_line: continue values = current_line.split(",") # 读取得分时直接转成整数,避免后续重复处理 score = int(values[2][:3]) scores.append(score) return scores def analyze_golf_scores(): scores = open_and_read_golf_scores() # 计算平均分 total = sum(scores) ave = total / len(scores) print("Average score =", ave) # 统计低于280的条目数 below_par = 0 for score in scores: if score < 280: below_par += 1 print("The number of scores below par is ", below_par) # 调用函数运行 if __name__ == "__main__": analyze_golf_scores()
主要修改点
- 读取文件时直接将得分转换为整数,从根源避免类型比较错误
- 修正缩进问题,所有功能逻辑都放在
analyze_golf_scores函数内部 - 修复平均分计算逻辑,用整个得分列表的长度计算平均值
- 重写低于280分的统计逻辑,用计数变量累加符合条件的条目数
- 改用
with上下文管理器操作文件,无需手动调用close方法,避免文件资源泄漏
内容的提问来源于stack exchange,提问作者amanda
相关产品推荐
相关产品推荐

