How can I check if an input is both a digit and a range? python

I would like to check if my input is a digit and a range (1,3) at the same time, and repeat the input until I get a satisfactory answer. Right now I am doing it this way, but the code is not quite clean and lightweight ... Is there a better way to do it? Maybe with a while loop?

def get_main_menu_choice():
    ask = True
    while ask:
        try:
            number = int(input('Chose an option from menu: '))
            while number not in range(1, 3):
                number = int(input('Please pick a number from the list: '))
            ask = False
        except: # just catch the exceptions you know!
            print('Enter a number from the list')
   return number

      

We will be grateful for your help.

+3


source to share


5 answers


I think the easiest way to do this is to remove the double loops. But if you want to work with both a loop and an error, you will end up with somewhat confusing code no matter what. I would personally go for:



def get_main_menu_choice():
    while True:    
        try:
            number = int(input('Chose an option from menu: '))
            if 0 < number < 3:
                return number
        except (ValueError, TypeError):
            pass

      

+1


source


If your integer number is between 1 and 2 (or in the range (1,3)), this already means that it is a digit!

while not (number in range(1, 3)):

      

which I would simplify:

while number < 1 or number > 2:

      



or

while not 0 < number < 3:

      

The simplified version of your code has an attempt, except only int(input())

:

def get_main_menu_choice():
    number = 0
    while number not in range(1, 3):
        try:
            number = int(input('Please pick a number from the list: '))
        except: # just catch the exceptions you know!
            continue # or print a message such as print("Bad choice. Try again...")
    return number

      

0


source


see if it works

def get_main_menu_choice():
    while True:
        try:
            number = int(input("choose an option from the menu: "))
            if number not in range(1,3):
                number = int(input("please pick a number from list: "))
        except IndexError:
            number = int(input("Enter a number from the list"))
    return number

      

0


source


If you need to do validation against non-numbers, you will need to add a few steps:

def get_main_menu_choice(choices):
    while True:
        try:
            number = int(input('Chose an option from menu: '))
            if number in choices:
                return number
            else:
                raise ValueError
        except (TypeError, ValueError):
            print("Invalid choice. Valid choices: {}".format(str(choices)[1:-1]))

      

Then you can reuse it for any menu by passing in a list of valid choices, e.g. get_main_menu_choice([1, 2])

or get_main_menu_choice(list(range(1, 3)))

.

0


source


I would write it like this:

def get_main_menu_choice(prompt=None, start=1, end=3):
    """Returns a menu option.

    Args:
        prompt (str): the prompt to display to the user
        start (int): the first menu item
        end (int): the last menu item

    Returns:
        int: the menu option selected
    """
    prompt = prompt or 'Chose an option from menu: '
    ask = True
    while ask is True:
        number = input(prompt)
        ask = False if number.isdigit() and 1 <= int(number) <= 3 else True
   return int(number)

      

0


source







All Articles