Summary
Use a while loop to keep asking the user for input, until they type a valid value.
Situation
You're asking a user to input a single piece of string data. You want ensure they type something valid.
Provides
A value guaranteed to be valid. Use the value in the rest of the code, without worrying it might be crazy.
Action
- Initialize input variable
- while Input is not valid:
- Ask user to input a value
- Normalize input
- if input not valid:
- Show error message
Example:
- # Initialize service_level
- service_level = ''
- # Is the service level valid?
- while service_level != 'g' and service_level != 'o' and service_level != 's':
- # Don't have a valid service level yet
- # Ask user to input the service level
- service_level = input('Service level (g=great, o=ok, s=sucked)? ')
- # Normalize input
- service_level = service_level.strip().lower()
- # Is the service level valid?
- if service_level != 'g' and service_level != 'o' and service_level != 's:
- # Show error message
- print('Please enter G, O, or S.')
Where referenced