3

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 6

2

I guess the most clean way of doing this would be to remove the double loops. But if you want both looping and error handling, you'll end up with somewhat convoluted code no matter what. I'd 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
Sign up to request clarification or add additional context in comments.

Comments

1
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())
``

1 Comment

Code only answers are discouraged on SO. Quality answers generally include an explanation, allowing users to quickly focus on & understand how relevant portions of your code solves the OP's question. Most upvotes are gained over time as future visitors learn something that they can apply to solve their own coding issues. Consider editing to add explanation or context. Thanks for your contribution, & welcome to SO.
0

see if this 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

Comments

0

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

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

which I would simplify to:

while number < 1 or number > 2:

or

while not 0 < number < 3:

A simplified version of your code has try-except around the int(input()) only:

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

3 Comments

But I need protection when someone inputs empty string(Enter) or letters. I need to ask them for input untill they input number 1 or 2.
Ah, I misunderstood your question. It seems that you are interested in handling the except!
@JeyKey I've added a simplified version of your code.
0

If you need to do validation against non-numbers as well you'll have 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 a list of valid choices, e.g. get_main_menu_choice([1, 2]) or get_main_menu_choice(list(range(1, 3))).

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.