-1

I want to be able to check that an input is an integer between 1 and 3, so far I have the following code:

userChoice = 0

while userChoice < 1 or userChoice > 3:
    userChoice = int(input("Please choose a number between 1 and 3 > "))

This makes the user re-enter a number if it is not between 1 and 3, but I want to add validation to ensure that a user cannot enter a string or unusual character that may result in a value error.

Tim
  • 43
  • 7

2 Answers2

3

Catch the ValueError:

Raised when a built-in operation or function receives an argument that has the right type but an inappropriate value

Example:

while userChoice < 1 or userChoice > 3:
    try:
        userChoice = int(input("Please choose a number between 1 and 3 > "))
    except ValueError:
        print('We expect you to enter a valid integer')

Actually, since the range of allowed numbers is small, you can operate directly on strings:

while True:
    num = input('Please choose a number between 1 and 3 > ')
    if num not in {'1', '2', '3'}:
        print('We expect you to enter a valid integer')
    else:
        num = int(num)
        break
vaultah
  • 44,105
  • 12
  • 114
  • 143
1

Alternatively try comparison of input in desired results, and break from the loop, something like this:

while True:
    # python 3 use input
    userChoice = raw_input("Please choose a number between 1 and 3 > ")
    if userChoice in ('1', '2', '3'):
        break
userChoice = int(userChoice)
print userChoice

Using Try/Except is a good approach, however your original design has a flaw, because user can still input like "1.8" which isn't exactly an integer but will pass your check.

Anzel
  • 19,825
  • 5
  • 51
  • 52