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

如何实现学分输入范围校验及学业进展结果判定程序?

问题修正与代码优化

需求回顾

  • 用户需输入通过学分、挂科学分、延期学分三个值
  • 输入的学分必须属于集合 {0,20,40,60,80,100,120},超出范围时显示 Out of range
  • 根据三个学分的合法组合(共28种,总学分需为120),输出对应的结果:
    • Progress:通过学分 = 120
    • Progress(module trailer):通过学分 = 100
    • Do not progress - module retriever:符合对应组合
    • Exclude:符合对应组合

现有代码的问题

  1. 输入函数未做范围校验,仅检查是否为整数
  2. 结果判断逻辑未先校验总学分是否为120(合法组合的总学分必须是120)
  3. 状态判断条件冗余且不严谨,覆盖不全
  4. 最后一行函数调用参数错误,且缺少循环终止机制

修正后的代码

range_of_credits = {0, 20, 40, 60, 80, 100, 120}

def credit_input(prompt, error_int='Integer required', error_range='Out of range'):
    while True:
        try:
            credit = int(input(prompt))
            # 校验学分是否在合法范围内
            if credit not in range_of_credits:
                print(error_range)
                continue
            break
        except ValueError:
            print(error_int)
    return credit

while True:
    pass_credits = credit_input('Enter the number of credits to pass: ')
    defer_credits = credit_input('Enter the number of credits to defer: ')
    fail_credits = credit_input('Enter the number of credits to fail: ')

    # 先校验总学分是否为120
    if pass_credits + defer_credits + fail_credits != 120:
        print('Total credits must be 120')
        continue

    # 判断结果状态
    if pass_credits == 120:
        print('Progress')
    elif pass_credits == 100:
        print('Progress(module trailer)')
    elif fail_credits >= 80:
        print('Exclude')
    else:
        # 剩余情况均为module retriever
        print('Do not progress - module retriever')

    # 询问是否继续输入
    choice = input('Would you like to enter another set of data? (y/n): ').strip().lower()
    if choice != 'y':
        break

关键修改说明

  1. 输入校验增强:在credit_input函数中加入范围验证,输入值不在合法集合时提示Out of range
  2. 总学分校验:添加总学分必须等于120的判断,确保输入组合合法
  3. 简化状态判断逻辑:
    • 先判断Progress和Progress(module trailer)的明确情况
    • 挂科学分≥80时直接判定为Exclude
    • 剩余合法组合统一归为Do not progress - module retriever,覆盖所有28种合法情况
  4. 添加循环终止机制:每次输出结果后询问用户是否继续,输入非y则退出程序
  5. 修正函数调用错误:移除无效的函数调用,规范变量命名提升可读性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 18:15:40