Python计算学生平均身高calAvgHeight方法ValueError报错求解
问题原因分析
- 你提供的
listOfStudentHeight.txt文件中,每行的姓名和身高是用多个空格分隔,并非代码中使用的制表符\t,且每行开头还带有#符号。调用line.split("\t")后得到的列表只有1个元素,取info[1]实际是包含姓名+身高的整行字符串,自然无法转换为float类型。 addUser方法的身高输入校验逻辑完全无效:input默认返回字符串,你没有对输入内容做转float的操作,就算输入非数字也不会触发ValueError,异常捕获等于无效摆设。calAvgHeight方法中计算平均身高的逻辑放在了循环内部,会每读一行就输出一次错误的平均值,不符合功能需求。with open语法会在代码块执行结束后自动关闭文件,末尾手动调用f.close()属于冗余代码。
修复后的完整代码
class CalUtils: def __init__(self): self.names = [] self.heights = [] self.totalStudentHeight = 0 self.totalStudentCount = 0 def addUser(self): name = input("Please enter your name:") # 修复身高输入校验逻辑 while True: try: # 输入后直接转float,校验 height = float(input("Please enter your height:")) height_str = str(height) break except ValueError: print("You have entered a non-numeric") f = open("listOfStudentHeight.txt", "a") f.write("\n" + name + "\t" + height_str) f.close() f = open("listOfStudentHeight.txt", "r") print(f.read()) f.close() def calAvgHeight(self): names = [] heights = [] total = 0 with open("listOfStudentHeight.txt", "r") as f: for line in f: line = line.strip() # 跳过空行 if not line: continue # 去掉行开头的#符号和多余空白 if line.startswith("#"): line = line.lstrip("#").strip() # 从右侧按空格分割1次,自动适配多空格、单空格的分隔场景 info = line.rsplit(maxsplit=1) # 跳过格式异常的行 if len(info) != 2: continue name, height_val = info # 二次校验身高可以转成数字 try: height_float = float(height_val) except ValueError: continue names.append(name) heights.append(height_float) total += height_float # 所有行处理完成后再计算平均 if len(names) > 0: avg = round(total / len(names), 2) print("The average height is " + str(avg)) else: print("暂无有效学生身高数据") Person = CalUtils() Person.addUser() Person.calAvgHeight()
内容的提问来源于stack exchange,提问作者user17594604
相关产品推荐
相关产品推荐

