Search code examples
pythondictionaryeoferror

Python EOFError for value in dictionary


Long time lurker, first time poster. Test cases are returning a Traceback EOFError for the country_name = input() line.

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

Nothing fancy, the code gets the value of a key in a dictionary (“data”) based on user input (“country_name”). I’ve tried running in multiple IDEs and it works fine for me, reindenting, tried str(input()) etc.

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')

UPDATED, improvements per 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

UPDATE: It turns out the test cases weren't passing, because the test cases were written so strictly that they were expecting a get() method. Once those were removed, the test cases passed once I added an exit per the modified code (above), per the comments below.


Solution

  • If the test case hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), this wil raise an EOFError. I can create the same error when I do Cmd+D in my Mac after running the program.

    The test case might be exiting in a similar fashion.

    Cant you just wrap it in a try-catch and ignore the EOFError as shown below:

    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