One-time numeric input validation

Tags
Summary
  • Get user input into a string variable.
  • Try to convert the data to numeric. If it fails, show an error message, and stop the program.
  • If it works, check whether the number is in the valid range (not too small, and not too large). If it fails, show an error message, and stop the program.
  • If both checks pass, you have a number you can use for calculations.
Situation

You want the user to enter a numeric value. If they enter a nonnumeric value, show an error message and stop the program.

Action

First, test whether the input is a number. Then test whether it is in the valid range.

Here's an example:

  1. ...
  2. user_input = float(input('Meal cost? '))
  3. # Test data type.
  4. try:
  5.     meal_cost = float(user_input)
  6. except ValueError:
  7.     print('Sorry, you must enter a number.')
  8.     sys.exit()
  9. # Test range.
  10. if meal_cost <= 0 or meal_cost > 1000000:
  11.     print('Sorry, please enter a number more than zero, and less than 1,000,000.')
  12.     sys.exit()
  13. ...

You need to import the sys module for lines 8 and 12.

You can use int instead of float in line 5.

Where referenced