Numeric validation loop

Summary

Loop while a data-OK flag is false:

    Set a data-OK flag to true.

    Check whether the data is numeric. If not, set the data-OK flag to false.

    If the data-OK flag is still true, do a range test. If the data is out of range, set the data-OK flag to false.

    Repeat for as many tests as you need.

Situation

You want to get a number from the user. Keep asking until they type a number that's in-range, and meets whatever other tests you have.

Action

Loop while a data-OK flag is false:

    Set a data-OK flag to true.

    Check whether the data is numeric. If not, set the data-OK flag to false.

    If the data-OK flag is still true, do a range test. If the data is out of range, set the data-OK flag to false.

    Repeat for as many tests as you need.

Sample code:

  1. # Get the cost of the meal.
  2. is_input_ok = False
  3. while not is_input_ok:
  4.     # Start off assuming data is OK.
  5.     is_input_ok = True
  6.     # Get input from the user.
  7.     user_input = input('Meal cost? ')
  8.     # Is the input numeric?
  9.     try:
  10.         meal_cost = float(user_input)
  11.     except ValueError:
  12.         print('Sorry, you must enter a number.')
  13.         is_input_ok = False
  14.     # Check the range.
  15.     if is_input_ok:
  16.         if meal_cost <= 0 or meal_cost > 1000000:
  17.             print('Sorry, please enter a number more than zero, and less than 1,000,000.')
  18.             is_input_ok = False
Where referenced