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

Python实现姓名录入与成绩平均计算时出现TypeError如何解决

错误原因排查
  • 传参错误:main函数中调用determine_outcome时,传入的参数是函数对象ask_score,而非计算后的平均分,这就是报错TypeError: '<=' not supported between instances of 'function' and 'int'的直接原因。你已经获取到了4个分数,需要先调用calc_average计算平均分,再把平均分传入determine_outcome。
  • 条件判断逻辑错误:
    • 条件顺序颠倒:第一个判断分支为user_score <=8,所有小于等于8的分数都会进入第一个分支,后续>=6<8、<=5的分支永远不会被触发,结合提示文案来看,第一个高分分支应该写成user_score >=8才符合“表现好”的逻辑
    • 多条件判断写法错误:user_score >=6 <8的写法不符合Python语法,正确写法为6 <= user_score <8
    • 分支覆盖不全:原有判断逻辑没有覆盖5~6分之间的分数,会出现无匹配分支的情况
  • 字符串格式化参数错误:你在format中传入了print_greeting、ask_score、print_teacher_greeting三个函数对象,输出只会显示函数的内存地址,并非你需要的用户名、平均分、老师姓名,应该使用之前已经存储的ask_name、计算好的平均分、ask_teacher_name三个变量。
  • 冗余代码问题:print_greeting、print_teacher_greeting中的str(print(...))写法完全无效,print函数返回值为None,外层套str没有任何意义。
修正后的完整代码
def user_name():
    ask_name = str(input("Enter your name: "))
    return ask_name

def print_greeting(ask_name):
    print("Your name is {0}.".format(ask_name))

ask_name = user_name()
print_greeting(ask_name)

def teacher_name():
    ask_teacher_name = str(input("What is the name of your computer science teacher?: "))
    return ask_teacher_name

def print_teacher_greeting(ask_teacher_name):
    print("Your computer science teacher's name is {0}.".format(ask_teacher_name))

ask_teacher_name = teacher_name()
print_teacher_greeting(ask_teacher_name)

def calc_average(score1, score2, score3, score4):
    average = (score1 + score2 + score3 + score4) / 4
    return average

def ask_score():
    score1 = float(input("Please enter score 1: "))
    score2 = float(input("Please enter score 2: "))
    score3 = float(input("Please enter score 3: "))
    score4 = float(input("Please enter score 4: "))
    return score1, score2, score3, score4

def determine_outcome(user_score):
    if user_score >= 8:
        print("Well done {0}, your average score was {1}. {2} would be proud of you.".format(ask_name, user_score, ask_teacher_name))
    elif 6 <= user_score < 8:
        print("A good effort, {0}, your average was {1}. {2} thinks you should check your work more carefully.".format(ask_name, user_score, ask_teacher_name))
    else:
        print("{0}, this is quite poor. Your average was only {1}. {2} has asked you to try harder please.".format(ask_name, user_score, ask_teacher_name))

def main():
    score1, score2, score3, score4 = ask_score()
    avg_score = calc_average(score1, score2, score3, score4)
    determine_outcome(avg_score)

main()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 23:45:02