Input validation is used to ensure the user can only type in valid values.
See also pages on decisions (if commands) and conditions.
General Algorithms
get input from user while input is not valid display error get input from user end while
repeat get input from user if input is not valid display error end while
Length Check
User must enter a string that has a minimum/maximum number of characters.
1 2 3 4 5 6 | # computer = input ( 'Enter computer ID:' ) while len (computer) ! = 14 : print ( 'Must have 14 characters' ) computer = input ( 'Enter computer ID:' ) # |
1 2 3 4 5 6 7 8 | # while True : computer = input ( 'Enter computer ID:' ) if len (computer) ! = 14 : print ( 'Must have 14 characters' ) else : break # |
Range Check
User must enter a number that is bigger/smaller than another number.
1 2 3 4 5 6 | # quantity = input ( 'Enter quantity:' ) while quantity < 1 : print ( 'Must be at least 1' ) quantity = input ( 'Enter quantity:' ) # |
1 2 3 4 5 6 7 8 | # while True : quantity = input ( 'Enter quantity:' ) if quantity < 1 : print ( 'Must be at least 1' ) else : break # |
Restricted Choice
User must enter a value that is in a list of valid strings or numbers
1 2 3 4 5 6 | # happy = input ( 'Are you happy?' ) while happy ! = 'Yes' and happy! = 'No' : print ( 'Enter Yes or No' ) happy = input ( 'Are you happy?' ) # |
1 2 3 4 5 6 7 8 | # while True : happy = input ( 'Are you happy?' ) if happy ! = 'Yes' and happy! = 'No' : print ( 'Enter Yes or No' ) else : break # |