Checking for an end of file with input()

Sometimes we want to design our code so we read a set of numbers from a file or from standard input without knowing in advance how many there are. When we run out of input (reach the end of file), we stop. Here is the naive way to do it. In this example we are reading from standard input, but we could just as well be reading a file one line at a time.

while True:
     n = eval(input("Enter n "))
     [do stuff using n]

The boolean Python variable True is always true, so the while loop might run forever, but when you reach the end of the input, Python quits with an error message. This is ugly. What we would like to do is to catch this error condition and exit gracefully. Here is how

while True:
     try:
         n = eval(input("Enter n "))
     except EOFError:
         break
     [do stuff using n]
[do stuff with the full dataset]

The try: statement tells Python that you are going to attempt something that might create an error condition. The statement(s) in the block below it will always be executed. The except statement allows for error handling. That statement works a bit like an if statement. If the except statement includes one of the Python error types, the statement(s) in the indented block below it will be executed. Here we break out of the while loop. Otherwise, control is passed to the statement after that block, which, in this case, will “do stuff” using the value that was read. If the except statement does not specify any error type, any error will cause it to execute the indented block. To find out what the error condition is called, run your code without catching the error, and Python will give it to you along with the error message when your code crashes.