How to check if input is digit and in range at the same time? Python

Viewed 4153

I would like to check if my input is digit and in range(1,3) at the same time and repeat input till I got satisfying answer. Right now I do this in this way, but the code is quite not clean and easy... Is there a better way to do this? Maybe with 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

Will be grateful for help.

6 Answers
def user_number():

    # variable initial
    number = 'Wrong'
    range1 = range(0,10)
    within_range = False

    while number.isdigit() == False or within_range == False:
        number = input("Please enter a number (0-10): ")

        # Digit check
        if number.isdigit() == False:
            print("Sorry that is not a digit!")

        # Range check
        if number.isdigit() == True:
            if int(number) in range1:
                within_range = True
            else:
                within_range = False

    return int(number)

print(user_number())
``
Related