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:
- ...
- user_input = float(input('Meal cost? '))
- # Test data type.
- try:
- meal_cost = float(user_input)
- except ValueError:
- print('Sorry, you must enter a number.')
- sys.exit()
- # Test range.
- if meal_cost <= 0 or meal_cost > 1000000:
- print('Sorry, please enter a number more than zero, and less than 1,000,000.')
- sys.exit()
- ...
You need to import the sys
module for lines 8 and 12.
You can use int
instead of float
in line 5.
Where referenced