Exception handling of type EOFError

1
while True:
    try:
        x = input().split()
        l.append(x)
    except EOFError:
        break

I have a problem in this code where I can not get an EOF of x, because if I do not type anything and just hit enter, it still receives the value and adds to the list. I would like to know what are the cases that python returns EOFError and how to solve this problem of mine.

    
asked by anonymous 05.07.2018 / 17:37

1 answer

2

Attention to the indentation of your code, block try/except must be one level below block while , see:

while True:
    try:
        x = input().split()
        l.append(x)
    except EOFError:
        break

To exit the loop, instead of just pressing Enter , use Ctrl + D if you are running your program on the Linux terminal or > Ctrl + Z if you are in the Windows terminal ( cmd.exe ).

The exception of type EOFError is thrown by the native function input() if she reads EOF from the default entry (keyboard).

When you just press the Enter key, input() does not throw an exception of type EOFError because it read something blank , which is different from a EOF .

In order to make input() throw an exception of type EOFError , you need to send EOF to the default entry pressed on the keyboard Ctrl + D on Linux or Ctrl + Z for the Windows console ( cmd.exe ).

The documentation describes the exception of type EOFError as:

  

exception EOFError

     

Raised when the input() function hits an end-of-file condition ( EOF )   without reading any data. (N.B .: the io.IOBase.read() and    io.IOBase.readline() methods return an empty string when they hit    EOF .)

Reference EOF and Ctrl+D

    
05.07.2018 / 18:11