0

Beginner here, looking for info on input validation.

I want the user to input two values, one has to be an integer greater than zero, the next an integer between 1-10. I've seen a lot of input validation functions that seem over complicated for these two simple cases, can anyone help?

For the first number (integer greater than 0, I have):

while True:
    try:
        number1 = int(input('Number1: '))
    except ValueError:
        print("Not an integer! Please enter an integer.")
        continue
    else:
        break

This also doesn't check if it's positive, which I would like it to do. And I haven't got anything for the second one yet. Any help appreciated!

Alan Kavanagh
  • 9,425
  • 7
  • 41
  • 65
rh1990
  • 880
  • 7
  • 17
  • 32

3 Answers3

6

You could add in a simple if statement and raise an Error if the number isn't within the range you're expecting

while True:
    try:
        number1 = int(input('Number1: '))
        if number1 < 1 or number1 > 10:
            raise ValueError #this will send it to the print message and back to the input option
        break
    except ValueError:
        print("Invalid integer. The number must be in the range of 1-10.")
Alan Kavanagh
  • 9,425
  • 7
  • 41
  • 65
  • The raise ValueError if statement was what I was missing, thanks! – rh1990 Jan 24 '17 at 16:03
  • 1
    This will send the control to the except block and then back to the start of the loop. Notice I've changed some code too - i.e the else block was removed and also the continue. You don't need to explicitly call continue unless you want to skip some code. Otherwise the loop will continue naturally – Alan Kavanagh Jan 24 '17 at 16:05
2

Use assert:

while True:
    try:
        number1 = int(input('Number1: '))
        assert 0 < number1 < 10
    except ValueError:
        print("Not an integer! Please enter an integer.")
    except AssertionError:
        print("Please enter an integer between 1 and 10")
    else:
        break
hansaplast
  • 11,007
  • 2
  • 61
  • 75
0
class CustomError(Exception):
   pass

while True:
    try:
       number1 = int(raw_input('Number1: '))
       if number1 not in range(0,9):
         raise CustomError
    break
except ValueError:
    print("Numbers only!")
except CustomError:
    print("Enter a number between 1-10!)
lukast94
  • 23
  • 1
  • 6