Python作业求助:保龄球赛事分数程序问题排查与修正
修正保龄球比赛数据录入与最高分统计代码
问题概述
作为Python新手,有两项作业任务待修正:
- 数据录入程序:收集参赛者姓名与保龄球分数存入
result.txt,要求用try-except确保分数在0-300范围内,但当前代码无法处理负分输入,且错误数据仍会写入文件。 - 最高分统计程序:读取文件后格式化展示所有内容、参赛人数及所有最高分参赛者信息,但当前代码仅能输出单个最高分,甚至会错误输出低分。
一、数据录入代码修正
原代码问题
try-except逻辑错误:判断分数范围后抛出异常,但输入负分或超300时,仍会执行i +=1和写入文件的操作,导致错误数据被保存,循环直接推进。- 输入的参赛者编号未被使用,属于冗余代码。
- 手动调用
f.close(),但with语句已自动管理文件关闭,无需重复操作。
修正后代码
print('-----Program for Bowling Tournament-----') n = int(input('Enter the number of students participating in the competition: ')) i = 1 with open('result.txt', 'w') as f: while i <= n: # 输入参赛者姓名 name = input(f'Enter name of student {i}: ') # 循环获取有效分数,直到输入符合要求 while True: try: score = int(input(f'Please enter bowling score for {name}: ')) if not (0 <= score <= 300): raise ValueError(f'{score} is not between 0 and 300') # 分数有效则跳出循环 break except ValueError as e: print(f'Error: {e}. Please try again.') # 写入有效数据到文件 f.write(f'{name} {score}\n') print(f'Successfully saved {name}\'s score.') i += 1 # 读取并展示已保存的所有数据 print('\n--- Saved Data ---') with open('result.txt') as f: print(f.read())
改进说明
- 将分数输入改为循环逻辑,直到用户输入有效分数才会推进流程,避免错误数据写入文件。
- 移除冗余的参赛者编号输入(若需要编号可保留并写入文件)。
- 利用
with语句自动管理文件生命周期,简化代码。 - 增加操作成功提示,提升交互体验。
二、最高分统计代码修正
原代码问题
- 遍历
file_content时实际是遍历单个字符,而非文件的每一行,无法正确解析数据。 - 未从文件行中拆分
name和score变量,直接使用未定义变量导致逻辑错误。 highest_score初始值设为1,若所有分数为0会错误识别最高分。- 使用集合存储姓名,集合会自动去重且初始化方式错误,无法保留所有最高分参赛者。
- 未实现展示所有内容、统计参赛人数的功能。
修正后代码
# Program 2: Highest Score Statistics print('-----Bowling Tournament Statistics-----') # 读取文件并解析所有参赛者数据 participants = [] with open('result.txt', 'r') as f: print('--- All Participants ---') for line in f: line = line.strip() if not line: continue # 拆分姓名与分数,处理姓名含空格的情况 name, score_str = line.split(maxsplit=1) score = int(score_str) participants.append((name, score)) print(f'Name: {name:10} Score: {score}') # 统计参赛总人数 total_participants = len(participants) print(f'\nTotal number of participants: {total_participants}') # 处理无数据的边界情况 if not participants: print('\nNo participant data found.') else: # 获取最高分及所有对应参赛者 highest_score = max(score for name, score in participants) top_participants = [name for name, score in participants if score == highest_score] print('\n--- Highest Score Information ---') print(f'Highest Score: {highest_score}') print('Participants with highest score:') for name in top_participants: print(f'- {name}')
改进说明
- 按行读取文件内容,正确拆分并解析每个参赛者的姓名和分数,存储到列表中。
- 实现展示所有参赛者信息、统计参赛人数的功能。
- 使用
max()函数直接获取最高分,再筛选出所有获得最高分的参赛者,避免逻辑错误。 - 增加空文件判断,处理无数据的边界情况。
内容的提问来源于stack exchange,提问作者Luong
相关产品推荐
相关产品推荐

