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

Python中main()函数无法调用执行其他自定义函数的解决咨询

Python成绩统计程序修复方案

原有代码问题

  • 输入逻辑错误:main函数中直接将多成绩输入转为int类型,不符合输入格式要求,会直接抛出异常
  • 作用域错误:calcAverages函数内调用了未传入的全局变量scores,且未导入依赖的sys模块
  • 参数匹配错误:examScores仅定义1个入参,原调用逻辑错误传入2个参数
  • 缺少启动入口:无触发main函数执行的逻辑,程序启动后不会运行

修复后完整代码

import sys

# The program displays the letter grade and associated message for each exam score
#   and the average exam score
# The program will not contain any repeated code and have a minimum of two functions besides Main.

def main():
    # 修复输入逻辑:先获取完整输入字符串,再拆分转换为整数列表
    score_input = input("Enter your test scores separate by spaces, no commas: ")
    scores = list(map(int, score_input.split()))
    # 遍历处理每个成绩
    for n in scores:
        # 先调用examScores获取等级,同时输出评价
        letter = examScores(n)
        # 调用showLetters输出格式化信息
        showLetters(n, letter)
    # 所有成绩处理完成后计算平均分
    calcAverages(scores)

# display test score
def showLetters(num, letterGrade):
    print(f"{num:.1f} is an {letterGrade}\n")

# display score message
def examScores(num):
    if 90 <= num <= 100:
        letterGrade = "A"
        print("Excellent Work")
    elif 80 <= num <= 89:
        letterGrade = "B"
        print("Nice job")
    elif 70 <= num <= 79:
        letterGrade = "C"
        print("Not bad")
    elif 60 <= num <= 69:
        letterGrade = "D"
        print("Room for improvement")
    else:
        letterGrade = "F"
        print("Go back and review")
    return letterGrade


# calculate average of all scores entered by user
def calcAverages(grades):
    # 修复变量引用错误:使用传入的grades参数而非未定义的scores变量
    avg = sum(grades) / len(grades)
    print("Average exam score: ", avg)

    # ask user to repeat or quit
    answer = str(input('Please enter "y" to run program again or "n" to exit: '))
    if answer.lower() == 'n':
        print('Thank you for using! Goodbye!')
        sys.exit()
    elif answer.lower() == 'y':
        main()

# 程序启动入口
if __name__ == "__main__":
    main()

调用逻辑说明

  • 程序启动后触发main函数运行,获取用户输入的多组成绩并转换为整数列表
  • 遍历每个成绩,先调用examScores输出对应评价,返回该成绩对应的字母等级
  • 将成绩数值和字母等级传入showLetters,输出格式化的成绩等级信息
  • 所有单条成绩处理完成后,调用calcAverages计算并输出平均分,同时询问用户是否重新运行程序

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 10:09:03