仅用if/else/elif实现Python成绩计算器:移除最低分功能求助
Python成绩计算器:用if/else/elif移除最低分并计算平均分
核心问题解决:用条件语句确定最低分
要仅通过if/else找出四个测试分数中的最低分,可以先初始化变量存储当前最低分,再逐个与其他分数比较更新:
# 初始化最低分为第一个测试分数 lowest_score = iTest1 # 依次与其他分数比较,更新最低分 if iTest2 < lowest_score: lowest_score = iTest2 if iTest3 < lowest_score: lowest_score = iTest3 if iTest4 < lowest_score: lowest_score = iTest4
修正原代码中的错误
- 输入合法性判断逻辑错误
原代码中sDrop的判断条件if sDrop != "Y" or "N" or "y" or "n"永远为True(非空字符串在布尔判断中为真),正确写法如下:
if sDrop not in ("Y", "y", "N", "n"): print("Enter Y or N to drop the lowest grade.") raise SystemExit
- 未定义
score变量
需要先根据是否移除最低分计算平均分,再进行等级判定。
完整修正代码
# Input sName = str(input("Name of person that we are calculating the grades for: ")) iTest1 = int(input("Test 1: ")) iTest2 = int(input("Test 2: ")) iTest3 = int(input("Test 3: ")) iTest4 = int(input("Test 4: ")) sDrop = str(input("Do you wish to drop the lowest grade Y or N? ")) # Test If Statements if iTest1 <= 0: print("Test scores must be greater than 0.") raise SystemExit if iTest2 <= 0: print("Test scores must be greater than 0.") raise SystemExit if iTest3 <= 0: print("Test scores must be greater than 0.") raise SystemExit if iTest4 <= 0: print("Test scores must be greater than 0.") raise SystemExit # 修正输入合法性判断 if sDrop not in ("Y", "y", "N", "n"): print("Enter Y or N to drop the lowest grade.") raise SystemExit # 用if语句确定最低分 lowest_score = iTest1 if iTest2 < lowest_score: lowest_score = iTest2 if iTest3 < lowest_score: lowest_score = iTest3 if iTest4 < lowest_score: lowest_score = iTest4 # 计算总分与平均分 total_score = iTest1 + iTest2 + iTest3 + iTest4 if sDrop.lower() == "y": score = (total_score - lowest_score) / 3 else: score = total_score / 4 # Grade Scale if score >= 97.0: grade = "A+" elif score >= 94.0 and score <= 96.9: grade = "A" elif score >= 90.0 and score <= 93.9: grade = "A-" elif score >= 87.0 and score <= 89.9: grade = "B+" elif score >= 84.0 and score <= 86.9: grade = "B" elif score >= 80.0 and score <= 83.9: grade = "B-" elif score >= 77.0 and score <= 79.9: grade = "C+" elif score >= 74.0 and score <= 76.9: grade = "C" elif score >= 70.0 and score <= 73.9: grade = "C-" elif score >= 67.0 and score <= 69.9: grade = "D+" elif score >= 64.0 and score <= 66.9: grade = "D" elif score >= 60.0 and score <= 63.9: grade = "D-" else: grade = "F" # 输出结果 print(f"\nCalculation for {sName}:") print(f"Average score: {score:.2f}") print(f"Final grade: {grade}")
说明
- 代码通过逐步比较的
if语句确定四个分数中的最低分,完全符合仅使用if/else/elif的要求。 - 修正了原代码中的逻辑错误,补充了结果输出部分,让功能更完整。
内容的提问来源于stack exchange,提问作者emily isaacs
相关产品推荐
相关产品推荐

