pythonpython-3.xvisual-studio-codeeoferror

Can't catch EOFError


What I expect from making this code is, I input some numbers, then when I input strings the output is 'Not Valid', but when I press enter without putting some value to input, the output is the sum of numbers that we input before. But when I run it on VSCode, whenever I press enter, the result always 'Not Valid', and can't get out of the loop.

For example, I input: 1 2 3 a z then the output I expect is: Not valid Not valid 6

I don't know what is wrong, I just learned python 2 months ago.

sum = 0
while True:
    try:
        sum += int(input())
    except ValueError:
        print('Not Valid')
    except EOFError:
        print(sum)
        break

Solution

  • When you don't input anything, input() will return the empty string. Converting it to an integer is invalid, so you get the ValueError:

    >>> input() # next line is empty because I just pressed Enter
    
    '' # `input()` returned the empty string
    >>> int('') # can't convert it to an integer
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ValueError: invalid literal for int() with base 10: ''
    

    To trigger EOFError, send the EOF signal with Ctrl + D:

    >>> input()
    ^DTraceback (most recent call last):
      File "<stdin>", line 1, in <module>
    EOFError
    

    Here the ^D represents me pressing Ctrl + D on the keyboard (not literally typing "^D").