Eoferror type exception treatment

Asked

Viewed 4,911 times

1

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

I’m having a problem with this code where I’m not getting an EOF from x, because if I don’t type anything and just hit enter, it still gets the value and adds to the list. I wonder what are the cases that python returns Eoferror and how to solve this my problem.

1 answer

6


Attention on the indentation of your code, the block try/except should be one level below the block while, look at you:

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 at the Windows terminal (cmd.exe).

The exception of type EOFError is launched by the native function input() in case she reads a EOF from the standard input (keyboard).

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

To make input() throw a type exception EOFError, you need to send a EOF for standard input pressed on keyboard Ctrl + D on Linux terminals or Ctrl + Z for the Windows console (cmd.exe).

The documentation describes the type exception 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

  • But when I use Ctrl+D on the terminal it simply shows this: D, then I hit enter and it takes that value as a string, it can help me?

  • @Angelogonçalvessalles: Surely you are on the Windows console, where the equivalent would be Ctrl + Z. See my latest edition.

  • Okay, now it worked, thank you very much.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.