Spring Deals - hours only!Up to 70% off on all courses and bundles.-Close
Introduction
The very basics of text files
with statement and exception handling
11. ValueError
Summary

Instruction

Great! Naturally, when an exception is thrown, we can do more than just print a custom error message. Consider this example:

while True:
  try:
    x = int(input('Provide a number: '))
    break
  except ValueError:
    print('That is not a number! Try again. ')

In the example above, we ask the user to provide a number using the input() function within a while True loop. input() provides a string from the user, so we want to convert it to a number using int(). Python Documentation states that int() throws a ValueError exception if the argument can't be converted to an integer.

In our case, two options are possible:

  • If int() converts user input successfully, the next line of code is executed, which is break: we escape the otherwise infinite while loop.
  • If int() fails and throws a ValueError, the try block is immediately interrupted. Then, break is never executed. Instead, the except block prints an error message, and the whole loop repeats in another iteration.

Exercise

Inside a loop, keep asking the user to provide a filename until it's a valid one and the file can be read.

When the filename is incorrect, print:

Could not read the file. Try another one.

When the filename is correct, simply print its contents.

You can test the correctness of the program for the animals.txt.

Stuck? Here's a hint!

Use a while True loop, as shown in the example. Use a try-except block, and catch any IOError.