One-time string input validation

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.

  1. service_level = input('Service level (g=great, o=ok, s=sucked)? ')
  2. # Normalize service_level input
  3. service_level = service_level.strip().lower()
  4. # Validate service_level input
  5. if service_level != 'g' and service_level != 'o' and service_level != 's':
  6.     print('Please enter G, O, or S.')
  7.     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