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

如何让Python成绩判定程序实现正确的循环重启功能?

问题描述

我写了一段Python程序用来判定成绩等级(通过Pass、延期Defer、不及格Fail),当前程序在输入不符合规则时会直接退出。我想实现程序结束后能根据需求重启的功能,尝试用while循环和函数实现但没成功,程序没法正常循环。以下是我的代码:

def inputPass(message):
  while True:
    try:
       userInput = int(input(message))
    except ValueError:
       print("Not an integer! Try again.")
       continue
    else:
       return userInput

def inputDefer(message):
  while True:
    try:
       userInput = int(input(message))
    except ValueError:
       print("Not an integer! Try again.")
       continue
    else:
       return userInput

def inputFail(message):
  while True:
    try:
       userInput = int(input(message))
    except ValueError:
       print("Not an integer! Try again.")
       continue
    else:
       return userInput

Pass = inputPass("Enter how many passes you got")
if((Pass) != 0 and (Pass != 20) and (Pass != 40) and (Pass != 60) and (Pass != 80) and (Pass != 100) and ( Pass != 120)):
        print("Out of range")
        exit()
Defer = inputDefer("Enter how many defers you got")
if ((Defer != 0) and (Defer != 20) and (Defer != 40) and (Defer != 60) and (Defer != 80) and (Defer != 100) and (Defer != 120)):
        print("out of range")
        exit()
Fail = inputFail("Enter how many fails you got")
if ((Fail != 0) and (Fail != 20) and (Fail != 40) and (Fail != 60) and (Fail != 80) and (Fail != 100) and (Fail != 120)):
        print("out of range")
        exit()

PDF = (Pass + Defer + Fail)

if PDF != 120:
    print("Total incorrect")
    exit()

if Pass == 120:
    print ("Progress")
elif Pass == 100:
    print("Progress (module trailer)")
elif Fail >= 80:
    print("Exclude")
else:
    print("Do not progress – module retriever")
解决方案

核心问题是你用exit()直接终止了程序,且未把完整流程放入循环。下面是修改后的代码,解决了循环重启问题,同时优化了冗余代码:

修改要点

  • 合并三个重复的输入函数为一个通用验证函数,减少冗余
  • 把整个成绩判定逻辑放入while True循环,实现重复运行
  • 移除exit(),用循环内的条件判断处理输入错误,让程序回到输入步骤而非直接退出
  • 添加用户选择,每次判定完成后询问是否继续运行
def validate_input(message):
    valid_scores = {0, 20, 40, 60, 80, 100, 120}
    while True:
        try:
            user_input = int(input(message))
            if user_input not in valid_scores:
                print("Out of range! Try again.")
                continue
            return user_input
        except ValueError:
            print("Not an integer! Try again.")

def main():
    while True:
        # 获取输入并验证
        pass_score = validate_input("Enter how many passes you got: ")
        defer_score = validate_input("Enter how many defers you got: ")
        fail_score = validate_input("Enter how many fails you got: ")

        # 检查总分
        total = pass_score + defer_score + fail_score
        if total != 120:
            print("Total incorrect! Please re-enter your scores.")
            continue

        # 判定成绩等级
        if pass_score == 120:
            print("Progress")
        elif pass_score == 100:
            print("Progress (module trailer)")
        elif fail_score >= 80:
            print("Exclude")
        else:
            print("Do not progress – module retriever")

        # 询问是否继续
        restart = input("\nDo you want to check another set of scores? (y/n): ").strip().lower()
        if restart != 'y':
            break

if __name__ == "__main__":
    main()

代码说明

  1. 通用输入函数validate_input:同时处理整数验证和范围检查,输入不符合要求时会持续提示重新输入,直到获取有效数据。
  2. 主循环while True:完整流程在循环内执行,每次判定完成后询问用户是否继续,输入'y'则重启流程,输入其他内容则退出循环。
  3. 总分检查:若总分错误,提示后回到输入步骤,而非直接终止程序。
  4. 模块化结构:用main()函数封装核心逻辑,代码更清晰易维护。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 05:10:30