Summary
- Get user input into a string variable.
- Normalize it to simplify value checking.
- Check whether the value is one of the valid values.
- If not, show an error message and stop the program.
Situation
You want the user to enter a string value from a limited set of valid values.
If it's invalid, you want to show an error message and stop the program.
Action
In this code, we want to get a valid input from the user. The response must be one of three valid values.
- service_level = input('Service level (g=great, o=ok, s=sucked)? ')
- # Normalize service_level input
- service_level = service_level.strip().lower()
- # Validate service_level input
- if service_level != 'g' and service_level != 'o' and service_level != 's':
- print('Please enter G, O, or S.')
- sys.exit()
Line 3 normalizes the input, striping leading/trailing spaces, and converting to lowercase. That gives the user flexibility in what they can type, while keeping the test in line 5 simple.
For line 7, you'll need to import the sys
module.
See the normalized input pattern.
Where referenced