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

Python字典取值时input()触发EOFError报错的排查与解决

Python国家经济排名查询脚本EOFError问题排查

我是长期潜水首次发帖的开发者,编写的代码功能为根据用户输入的国家名从data字典中查询对应经济排名,执行测试用例时,country_name = input()行触发EOFError回溯,报错信息如下:

Traceback (most recent call last):
    File "/usercode/file0.py", line 16 in <module> 
    country_name = input()
EOFError: EOF when reading a line

该代码在多个IDE中运行均正常,我尝试过重缩进、使用str(input())等方案都未解决问题,原代码如下:

data = {
    'Singapore': 1,
    'Ireland': 6,
    'United Kingdom': 7,
    'Germany': 27,
    'Armenia': 34,
    'United States': 17,
    'Canada': 9,
    'Italy': 74
}
 
for key, value in data.items():
    print(key, value)
 
while True:
    country_name = input()
 
    if country_name in data.keys():
        print("The economic rank is: ", data[country_name])
    else:
        print('Not found')

后续我根据评论建议优化代码,添加了EOFError异常捕获、查询到结果后直接退出的逻辑,优化后代码如下:

data = {
    'Singapore': 1,
    'Ireland': 6,
    'United Kingdom': 7,
    'Germany': 27,
    'Armenia': 34,
    'United States': 17,
    'Canada': 9,
    'Italy': 74
}

for key, value in data.items():
    print(key,value)

try:
    while True:
        country_name = input("Enter a country: ")

        if country_name in data.keys():
            print(f"The economic rank of {country_name} is {data[country_name]}.", flush=True)
            exit()
        else:
            print("Country not found.")

except EOFError:
    pass

最终排查发现测试用例不通过的原因是测试用例强制要求使用get()方法,移除该要求后,添加了退出逻辑的优化代码顺利通过测试。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 23:42:02