The Check Valid Input Program

The following mini-program demonstrates the use of try..except.

We will look at exceptions in more detail later on; however, it is important to see try and except early on.

1. A Program That Fails

Consider the following program.

num_string = input("Please enter a number:\n")

# try to convert the number using float()
# this will fail if the user doesn't enter anything valid. e.g. hello
x = float(num_string)

print(f"{x} + 5 = {x+5}")

If you enter something which is not a number, Python will throw an exception, in particular, a ValueError.

2. Validating the User Input

We can fix this issue by catching this exception using the try...except statement.

input_valid = False

while not input_valid:
  num_string = input("Please enter a number:\n")
  try:
    num = float(num_string)
    input_valid = True
  except ValueError:
    print("Input is not a valid number.\n")

print(f"{num} + 5 = {num+5}")

Here the program attempts to convert num_string to a float.

If this throws an exception, then we trigger the except block and print out Input is not a valid number.. Note that the line input_valid = True is not executed and thus input_valid remains set to False. Therefore, we ask the user for another number.

This will continue until the user enters input that does not trigger the exception and input_valid is set to True.