Python EOFError: EOF when reading a line
EOFError: EOF when reading a line
EOF stands for End Of File, which here means the end of the input. Each call to input() takes one line from the input, and you get this error when there is no line left to take. It is less that your code is wrong and more that the number of input() calls does not match the number of input lines.
Cause 1. The input box is empty
If you run the program without giving it any input, the very first input() raises the error. Online runners and judge sites often have a separate box where you type the input in advance.
Wrong code
name = input()print("hello", name)Traceback (most recent call last): File "main.py", line 1, in <module> EOFError: EOF when reading a line
Fixed code
First type a value into the input box and run it again. There is nothing to fix in the code.
If your program may really get no input, you can use try and except EOFError to decide what to do in that case.
try: name = input()except EOFError: name = "guest"print("hello", name)hello guest
Cause 2. You called input() more times than there are input lines
One input() reads one line. If two values are on one line and you call input() twice, the first call takes the whole line and the second has no line to read.
Wrong code
a = input()b = input()print(b, a)mina jun
Traceback (most recent call last): File "main.py", line 2, in <module> EOFError: EOF when reading a line
Fixed code
For values on the same line, call input() once and separate them with split().
Reading one line too many in a loop is the same problem. If you should read n lines, where n comes from the first line, but you loop with range(n + 1), the last pass raises this error.
Cause 3. You read with while True without knowing how many lines there are
In a problem that says "read until the input ends", putting input() inside while True: raises this error on the pass after all the lines have been read, and the program stops. It never reaches the line that prints the total.
Wrong code
total = 0while True: total += int(input())print(total)3 5 7
Traceback (most recent call last): File "main.py", line 3, in <module> EOFError: EOF when reading a line
Fixed code
Loop over sys.stdin with for. It repeats only while there are lines, and the loop ends when the input ends.
import sys total = 0for line in sys.stdin: total += int(line)print(total)3 5 7
15
You can also keep while True: and catch the end with try: ... except EOFError: break.
What to check when you see this error
- First check that the input box has something in it.
- The number after
linein the error message is the line of theinput()that had no line to read. Count how many timesinput()was called before it. - Compare the number of input lines with the number of
input()calls. Several values on one line means oneinput()and asplit(). - In a loop, check that it does not repeat one time more than there are lines.
- If the problem does not say where the input ends, read with
for line in sys.stdin:.