-1

I have this code as shown below and I would like to make a function which has a try and except error which makes it so when you input anything other than 1, 2 or 3 it will make you re input it. Below is the line which asks you for your age.

    Age = input("What is your age? 1, 2 or 3: ")

Below this is what I have so far to try and achieve what I want.

   def Age_inputter(prompt=' '):
        while True:
            try:
                return int(input(prompt))
            except ValueError:
                print("Not a valid input (an integer is expected)")

any ideas?

EDoggyDog
  • 17
  • 1
  • 5

2 Answers2

0

add a check before return then raise if check fails:

def Age_inputter(prompt=' '):
        while True:
            try:
                age = int(input(prompt))
                if age not in [1,2,3]: raise ValueError
                return age
            except ValueError:
                print("Not a valid input (an integer is expected)")
R Nar
  • 5,465
  • 1
  • 16
  • 32
0

This may work:

def Age_inputter(prompt=' '):
    while True:
        try:
            input_age = int(input(prompt))
            if input_age not in [1, 2, 3]:
                # ask the user to input his age again...
                print 'Not a valid input (1, 2 or 3 is expected)'
                continue
            return input_age
        except (ValueError, NameError):
            print 'Not a valid input (an integer is expected)'