We use the standard algorithm input validation to check that the user is entering a value that is expected by the program. In the example below our function is used to check that the entered integer is between a max and min value.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | def getValidInt(fMin,fMax): print ( "Please enter a number between" , str (fMin), "and" , str (fMax)) number = int ( input ()) while number<fMin or number>fMax: print ( "Sorry try again" ) print ( "Please enter a number between" , str (fMin), "and" , str (fMax)) number = int ( input ()) return number def main(): min = - 100 max = 100 number1 = getValidInt( min , max ) number2 = getValidInt( 1 , 20 ) print (number1,number2) main() |
The function follows the AREA standard algorithm, that is Ask Repeat Error Ask. so
- Ask for valid number
- Repeat While number not valid
- Display Error
- Ask for valid number
Too remember this mnemonic easier think Jonathan Ross for step 2, as in Python we would use a While.
The code above makes use of local variables as well as formal and actual parameters. Can you spot them?