Higher – Input Validation (Revision)

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.

 

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

  1. Ask for valid number
  2. Repeat While number not valid
  3.     Display Error
  4.     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?