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

Python聊天机器人提交至自动grader时触发EOFError问题求助

EOFError 问题解决:自动 grader 运行聊天机器人代码报错处理

报错信息

Test Failed: b'Traceback (most recent call last):\n  File "/autograder/source/q1.py", line 17, in <module>\n    mood = input("How are you doing today?\\n")\nEOFError: EOF when reading a line'

原始代码

good_mood_set = {"Good", "I’m great", "I’m good", "Fine"}
bad_mood_set = ("Bad", "Not Okay", "I’m not feeling good")
mood = input("How are you doing today?
")
if mood in bad_mood_set:
    print("Have some time to yourself to recharge!")
elif mood in good_mood_set:
    print("I’m glad you’re feeling well, " + name + ".")
else:
    print("I see!")
age = input("How old are you?
")
if mood in good_mood_set and age >= "18":
    print("You are ready to drive.
")
else:
    print("Still taking the bus!
")

问题分析

  1. EOFError 触发原因:自动 grader 以非交互式方式运行代码,不会手动输入内容,直接调用input()会因没有输入来源抛出该错误。
  2. 代码还存在其他问题:
    • name变量未定义,会触发NameError
    • 多行字符串写法错误(比如input("How are you doing today?\n")的换行写法不符合语法)
    • 年龄用字符串比较age >= "18"是字典序对比,不是数值逻辑对比
    • 字符串拼接方式繁琐且易出错

修正方案

把逻辑封装成函数,用参数接收输入值,既适配自动 grader 的测试方式,也保留本地交互式测试的可能,同时修复其他语法和逻辑错误。

修正后的代码

def chat_bot(name, mood_input, age_input):
    good_mood_set = {"Good", "I’m great", "I’m good", "Fine"}
    bad_mood_set = {"Bad", "Not Okay", "I’m not feeling good"}
    
    # 处理情绪响应
    if mood_input in bad_mood_set:
        print("Have some time to yourself to recharge!")
    elif mood_input in good_mood_set:
        print(f"I’m glad you’re feeling well, {name}.")
    else:
        print("I see!")
    
    # 处理年龄相关响应
    try:
        age = int(age_input)
        if mood_input in good_mood_set and age >= 18:
            print("You are ready to drive.")
        else:
            print("Still taking the bus!")
    except ValueError:
        print("Please enter a valid age.")

# 本地交互式测试用(自动grader调用时可注释或保留)
# if __name__ == "__main__":
#     user_name = input("What's your name? ")
#     user_mood = input("How are you doing today? ")
#     user_age = input("How old are you? ")
#     chat_bot(user_name, user_mood, user_age)

关键说明

  • 自动 grader 可直接调用chat_bot函数并传入测试参数,避免input()等待输入导致的EOFError。
  • 保留本地测试代码块,取消注释即可在IDE终端按原有方式运行。
  • 用f-string简化字符串拼接,同时增加年龄输入的异常处理,提升代码健壮性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 18:20:33