Python 字典中值的 EOFError

Python EOFError for value in dictionary

长期潜伏者,第一次海报。测试用例正在为 country_name = input() 行返回一个 Traceback EOFError。

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

没什么特别的,代码根据用户输入(“country_name”)获取字典(“数据”)中的键值。我在多个 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')

已更新,每个 comments/answers 的改进:

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() 方法。一旦这些被删除,一旦我根据下面的评论根据修改后的代码(上面)添加了一个出口,测试用例就通过了。

如果测试用例命中 EOF(*nix:Ctrl-D,Windows:Ctrl-Z+Return),这将引发 EOFError。当我在 运行 程序之后的 Mac 中执行 Cmd+D 时,我可以创建相同的错误。

测试用例可能以类似的方式退出。

你能不能把它包装在一个 try-catch 中并忽略 EOFError,如下所示:

try:
    while True:
        country_name = input()

        if country_name in data.keys():
            print("The economic rank is: ", data[country_name])
        else:
            print('Not found')
except:
    pass