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.
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.
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:
- # Get the cost of the meal.
- is_input_ok = False
- while not is_input_ok:
- # Start off assuming data is OK.
- is_input_ok = True
- # Get input from the user.
- user_input = input('Meal cost? ')
- # Is the input numeric?
- try:
- meal_cost = float(user_input)
- except ValueError:
- print('Sorry, you must enter a number.')
- is_input_ok = False
- # Check the range.
- if is_input_ok:
- if meal_cost <= 0 or meal_cost > 1000000:
- print('Sorry, please enter a number more than zero, and less than 1,000,000.')
- is_input_ok = False