You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在while循环中嵌套for循环实现Python测验录入功能遇阻求助

测验成绩录入程序优化

你提到想用递减式for i in range()写法控制测验录入,同时要保留exit退出功能,还要修复原代码里的逻辑问题(比如用单个分数判断及格而非平均分)。下面是调整后的代码:

name = input("Enter your first name: ")
Q = int(input("How many quizzes have you taken? "))
quiz_records = {}
minimum_quizzes = 3  # 与提示信息统一,确保至少需录入3个测验
passing_score = 70

# 先校验测验数量是否符合要求
if Q < minimum_quizzes:
    print(f"You need at least {minimum_quizzes} quiz scores to enter.")
    exit()

# 用递减for循环控制录入次数,同时支持提前退出
for remaining in range(Q, 0, -1):
    print(f"\nYou have {remaining} quiz(zes) left to enter. Type 'exit' to quit early.")
    
    # 处理测验标题输入,确保非空且支持退出
    while True:
        quiz_title = input("Enter your quiz title: ").strip()
        if quiz_title.lower() == "exit":
            print("Exiting early.")
            exit()
        if quiz_title:
            break
        print("Please enter a valid quiz title (can't be empty).")
    
    # 处理测验分数输入,支持退出和非数字校验
    while True:
        quiz_grade_input = input("Enter your quiz grade: ").strip()
        if quiz_grade_input.lower() == "exit":
            print("Exiting early.")
            exit()
        try:
            quiz_grade = float(quiz_grade_input)
            break
        except ValueError:
            print("Please enter only numbers for a grade.")
    
    # 将有效数据存入字典
    quiz_records[quiz_title] = quiz_grade

# 输出测验信息汇总
print(f"\nHello {name.capitalize()}, here is your entered quiz information: ")
for title, grade in quiz_records.items():
    print(f"For quiz '{title}' you received {grade}%")

# 计算平均分并判断是否及格
average_score = sum(quiz_records.values()) / len(quiz_records)
if average_score >= passing_score:
    print(f"\nYour average quiz score is {average_score:.1f}%, which is above the minimum of {passing_score}%. Congrats, you've passed!")
else:
    print(f"\nSorry, your average quiz score is {average_score:.1f}%, you need an average of {passing_score}% to pass.")

关键调整说明:

  • 用for remaining in range(Q, 0, -1)实现递减式录入提示,让用户清晰看到剩余需录入的测验数量
  • 拆分标题和分数的输入逻辑,各自用循环处理空输入、exit指令和格式错误,确保输入有效才进入下一步
  • 修正原代码中用最后一个测验分数判断及格的错误,改为用真实平均分进行判断
  • 优化变量命名(如list1改为quiz_records),提升代码可读性
  • 保留随时输入exit提前退出的功能,同时不破坏正常录入流程

内容的提问来源于stack exchange,提问作者Greg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 15:07:49