Python 5.5 : Exercise : Handling invalid input

Now we want to improve the program by handling invalid input. If we run the code and type something that is not a number, Python crashes with an exception coming from the conversion to int. The traceback points to the call site and then to the conversion line inside the function. Our exercise is to catch this error and ask the user again until they give us a valid number.

try / except inside a while loop

We modify the ask_number function with a try block around the conversion. If the conversion fails, the except branch prints "error, you have to enter a number, retry" instead of crashing. To keep asking until a valid value is given, we wrap the whole thing in a while loop that runs as long as the integer answer is still zero (its initial value).

int_answer = 0
while int_answer == 0:
    try:
        str_answer = input("What is the magic number? ")
        int_answer = int(str_answer)
    except:
        print("Error, you have to enter a number, retry")

When we run the program again and type garbage, the error message appears and the prompt comes back. As soon as we enter a real digit such as 3 or 5, the loop exits and the program continues normally. In the next video we will go one step further and reject values that are outside the allowed minimum and maximum range.

Summary

This exercise demonstrates how to handle invalid user input in Python using error handling and loops. When users enter non-numeric data, a conversion error occurs, triggering an exception. The solution uses a try/except block combined with a while loop to keep prompting the user until they enter a valid number, with a clear error message guiding them to input a numeric value.

Key points

  • Recognize when invalid input causes conversion errors (line 6) when casting strings to numbers
  • Implement try/except blocks to catch and handle ValueError exceptions gracefully
  • Use a while loop to repeatedly request input until valid data is received
  • Provide user-friendly error messages instructing them to enter a valid number
  • Validate input before attempting numeric operations to prevent program crashes
  • Apply this pattern for handling both type conversion errors and range validation (min/max numbers)

FAQ

What happens when a user enters invalid input like random text instead of a number?

A conversion error is raised at the point where the string is converted to a number (typically line 6). Without error handling, this crashes the program. With try/except, the error is caught and the user receives a clear message asking them to enter a valid number.

How do we ensure users keep entering input until they provide a valid number?

Use a while loop that wraps the input conversion. The loop continues until the conversion succeeds without raising an exception, effectively trapping the user in the input prompt until valid numeric data is received.

Can this pattern also handle min and max number validation?

Yes. Beyond catching conversion errors, you can add additional conditional checks after successful conversion to validate that the number falls within an acceptable range (min/max boundaries), triggering re-prompts for out-of-range values.