Skip to Content

What an EOFError in Python is – Nailed it!

What an EOFError in Python is – Nailed it!

In Python, an EOFError is an exception that gets raised when functions such as input() and raw_input() return end-of-file (EOF) without reading any input.

Let’s take two numbers from the user, add them up, and display the result. The input() function takes an input from the user and converts it to a string.

Since we want to add two numbers, we need to convert the string to int. In Python  2.x, the raw_input() function is similar to the input() function in Python 3.x.

 

Consider the following example:

 

#python 3.6
value1 = int(input("Enter value 1: "))
value2 = int(input("Enter value2: "))
result = value1 + value2
print(f"The sum of {value1} and {value2} is: {result}")

 

If the user enters both values correctly, then the program will run without any EOFError Exception.

Enter value1: 10
Enter value2: 5
The sum of 10 and 5 is: 15

 

Now, let’s see what happens if we press Ctrl + D to quit the process when the input is being taken.

 

What an EOFError in Python is

What an EOFError in Python is

 

As you can see in the above output, an EOFError exception gets raised as the function returns without taking any data.

 

Handling an EOFError Exception

We can handle this exception using the try and except block. The suspicious code is added inside the try block, and the exception handling is done in the except block.

If no exception gets raised, i.e., the user inserts both inputs correctly, then the try block will run only. Otherwise, the except block will get control when an exception occurs.

Note that we only consider the EOFError exception here.

 

try:
  value1 = int(input("Enter value 1: "))
  value2 = int(input("Enter value2: "))
  result = value1 + value2
  print(f"The sum of {value1} and {value2} is: {result}")
except EOFError as e:
  print("End-Of-File when reading input")
 

 

EOFError exception output

EOFError exception output

 

Conclusion

Thansk for reading this blog post about what an EOFError in Python is. I hope this article clarified under what circumstances you might come across such an error and how to prevent it.

Happy coding!

Read about how to loop back to the beginning of a program in Python now.