String validation loop

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
  1. Initialize input variable
  2. while Input is not valid:
  3.     Ask user to input a value
  4.     Normalize input
  5.     if input not valid:
  6.         Show error message

Example:

  1. # Initialize service_level
  2. service_level = ''
  3. # Is the service level valid?
  4. while service_level != 'g' and service_level != 'o' and service_level != 's':
  5.     # Don't have a valid service level yet
  6.     # Ask user to input the service level
  7.     service_level = input('Service level (g=great, o=ok, s=sucked)? ')
  8.     # Normalize input
  9.     service_level = service_level.strip().lower()
  10.     # Is the service level valid?
  11.     if service_level != 'g' and service_level != 'o' and service_level != 's:
  12.         # Show error message
  13.         print('Please enter G, O, or S.')
Where referenced